1. The Select operator is used to perform a projection over a sequence, based on the arguments passed to the operator. Source data are enumerated and results are yielded based on the selector function for each element. The resulting collection can be a direct pass-through of the source objects, a single-field narrowing, or any combination of fields in a new object. Replace the previous query to create a direct projection:
static void OperatorQuery()
{
var db = new NorthwindDataContext();
var productsWithCh = from p in db.Products
where p.ProductName.Contains("Ch")
select p;
}
This query restricts the source data based on ProductName and then selects the entire Product.
2. Add the following lines to create a single-value projection:
static void OperatorQuery()
{
var db = new NorthwindDataContext();
var productsWithCh = from p in db.Products
where p.ProductName.Contains("Ch")
select p;
var productsByName = db.Products
.Where(p => p.UnitPrice < 5)
.Select(p => p.ProductName);
}
This query restricts based on unit price and then returns a sequence of product names.
3. Add the following lines to create a multi-value projection by using an anonymous type:
static void OperatorQuery()
{
var db = new NorthwindDataContext();
var productsWithCh = from p in db.Products
where p.ProductName.Contains("Ch")
select p;
var productsByName = db.Products
.Where(p => p.UnitPrice < 5)
.Select(p => p.ProductName);
var productsDetails = db.Products
.Where(p => p.Discontinued)
.Select(p => new { p.ProductName, p.UnitPrice });
}
Notice that the type returned in this example was never explicitly declared. The compiler has created this anonymous type behind the scenes, based on the data types of its members.
4. Finally, display the results with the following code: