C# LINQ Projection – Select and SelectMany Operators

Updated on     Kisan Patel

Projection helps us developer to retrieve desired result from the collection.

The Select and SelectMany are the Projection operators used in LINQ. Select works with one collection whereas SelectMany works with more than one collection.

The Select clause in LINQ performs function just as the Select statement in SQL and it specifies which elements are to be retrieved.

For Example, Select all the customers from Customers table.

NorthwindEntities _db = new NorthwindEntities();
IEnumerable Customers = from customers in _db.Customers
                                  select customers;

… would translate to …

NorthwindEntities _db = new NorthwindEntities();
var Customer = _db.Customers;

You can also select specific column using Select operators. For example, Select CustomerId, CompanyName, Country from Customers table.

NorthwindEntities _db = new NorthwindEntities();
var Customers = from customers in _db.Customers
                                    select new
                                    {
                                        CustomerId = customers.CustomerID,
                                        CompanyName = customers.CompanyName,
                                        Country = customers.Country
                                    };

… would translate to ..

NorthwindEntities _db = new NorthwindEntities();
var Customer = _db.Customers
                    .Select(x => new { CustomerId = x.CustomerID, CompanyName = x.CompanyName, Country = x.Country });

The SelectMany operator is useful when working with a sequence of sequences.

SelectMany collapses many elements into a single collection. The resulting collection is of another element type. We specify how an element is transformed into a collection of other elements. The SQL equivalent of SelectMany is INNER JOIN, LEFT OUTER JOIN and CROSS JOIN.

For example, the following LINQ query shows how to join Customers and Orders table.

NorthwindEntities _db = new NorthwindEntities();
var orders = _db.Customers
                .Where(x => x.Country == "USA" && x.Region == "WA")
                .SelectMany(x => x.Orders);

foreach (var order in orders)
    Console.WriteLine(order.Customer.CompanyName + " - " + order.OrderID);

LINQ-SelectMany-Example

You must be wondering about the difference between the Select and SelectMany operators. Both the methods are used to produce a result value from a source of values.

However, the difference lies in the result value. The Select() is used to produce one result value for every source value. The result value is a collection that has the same number of elements from the query.

In contrast, the SelectMany() produces a single result that contains a concatenated collection from the query.


C# LINQ

Leave a Reply