Sunday, July 22, 2012

C# LINQ - SELECT clause

This post is part of a series called LINQ Examples that brings practical examples of using LINQ in C#.

This time we'll concentrate our attention on SELECT clause. This kind of operators are called LINQ Projection Operators. First example shows use of SELECT with Anonymous Types. We produce a sequence of employees containing employee name and create a new type on the fly called ProjName which indicates the first project that specific employee has participated.
List<Employee> employees = GetEmployeeList();

var emps =
    from e in employees
    select new { e.EmployeeName, ProjName = e.Projects[0].ProjectCode };

foreach (var e in emps)
{
    Console.WriteLine("{0} worked on project {1}.", e.EmployeeName, e.ProjName);
}

/* Output:   
John worked on project Orlando.
Tomas worked on project Orlando.
Marina worked on project Orlando.
Susan worked on project Rocket.
Lucas worked on project Orlando.
*/
In the next example we select all employees which participated only in one project with budget larger than 900.

List<Employee> employees = GetEmployeeList();

var emps =
    from e in employees
    where e.Projects.Count() < 2
    from p in e.Projects
    where p.ProjectBudget >= 1000
    select new { e.EmployeeName, p.ProjectCode, p.ProjectBudget };

foreach (var e in emps)
{
    Console.WriteLine("{0} - Project Code: {1} - Project Budget: {2}.", 
            e.EmployeeName, e.ProjectCode, e.ProjectBudget);
} 

/* Output:   
Suzan - Project Code: Rocket - Project Budget: 7000.
*/

No comments:

Post a Comment