projection operator in linq
The projection operators used in LINQ are Select and SelectMany clauses. These operators transform an object into another object with different properties. A developer can define his own type dynamically and transform the query result into a new type. The difference between the select and SelectMany is that the Select clause works with one collection whereas SelectMany clause can work with more than one collection.
The below example code demonstrates how to use projections in LINQ to SQL query. Observe the below query. Using a projection operator Select, the query returns an anonymous type with two members - Customer Name and address.
Instead of selecting the entire customer object, we will use select operator to retrieve only some properties of customer object by creating an anonymous type on the fly.
SalesDBDataContext dataContext = new SalesDBDataContext();
var custQuery =
from cust in dataContext.Customers
select new
{ cust.CustomerId,
customerName = new { cust.CustomerId, cust.Name },
ContactAdd = new { cust.Address }
};
foreach (var cusObj in custQuery)
{
Console.WriteLine("ID = {0}, Name = {1},Address = {2}",
cusObj.CustomerId, cusObj.ContactAdd, cusObj.customerName);
}
Console.ReadLine();
The above code creates an anonymous type which consists of three properties- called CustomerId, customerName and ContactAdd based on the customer object.
When the projection returns anonymous type, we use the var keyword to assign the result to the variable .