Select

Projection to an anonymous type

In order to influence the resulting type, you can use projections. You can create an anonymous type just for CustomerID and CompanyName like this:

var customers =
    context.Customers
        .Select(c => new
        { 
            CustomerID = c.CustomerID,
            CompanyName = c.CompanyName
        })
        .ToList();

With help of the Select method you can easily create new flat objects on the fly, pulling data from different parts of the source:

var customersWithDetails =
    context.Customers
        .Select(c => new {
            CompanyName = c.CompanyName,
            NoOfOrders = c.Orders.Count,
            TotalFreight = c.Orders.Sum(o => o.Freight)
        })
        .ToList();

Projection to a single type

If all what you need is a list of a single property, you can get it through Select method in a similar way:

List<string> companyNames =
    context.Customers
        .Select(c => c.CompanyName)
        .ToList();

Getting a single result

You can get a single result of a simple type by combining the Select method with a First method. The following example shows the CompanyName of the company with most orders:

string companyName =
    context.Customers
        .OrderByDescending(c => c.Orders.Count)
        .Select(c => c.CompanyName)
        .First();

Should you have any questions or found a mistake that needs correcting, feel free to send an email to: info [at] linqtutorial [dot] info


Advertisements :