LINQ Queries With Example in c#, LINQ For Beginners

LINQ Queries With Example in c#, LINQ For Beginners

In this article, you will learn some LINQ queries with examples. We will use the following Employee and Standard collection for our queries.

IList<Employee> EmployeeList = new List<Employee>() { 
    new Employee() { EmployeeID = 1, EmployeeName = "John", Age = 18, StandardID = 1 } ,
    new Employee() { EmployeeID = 2, EmployeeName = "Ramu",  Age = 21, StandardID = 1 } ,
    new Employee() { EmployeeID  = 3, EmployeeName = "Bill",  Age = 18, StandardID = 2 } ,
    new Employee() { EmployeeID = 4, EmployeeName = "Ram" , Age = 20, StandardID = 2 } ,
    new Employee() { EmployeeID = 5, EmployeeName = "Shyam" , Age = 21 } 
};

IList<Standard> standardList = new List<Standard>() { 
    new Standard(){ StandardID = 1, StandardName="Standard 1"},
    new Standard(){ StandardID = 2, StandardName="Standard 2"},
    new Standard(){ StandardID = 3, StandardName="Standard 3"}
};

Select Multiple and where operator

var std_Names = EmployeeList.Where(s => s.Age > 18)
                              .Select(s => s)
                              .Where(st => st.StandardID > 0)
                              .Select(s => s.StudentName);

Output

Ramu

Ram

LINQ Group By and select collection

Use the overload of GroupBy you are currently using.

items.GroupBy(item => item.Order.Customer, 
              (key, group) =>  new { Customer = key, Items = group.ToList() }).ToList()
items.GroupBy(item => item.Order.Customer)
     .Select(group => new { Customer = group.Key, Items = group.ToList() }).ToList()

2021-10-03