CHAPTER 12 LINQ TO OBJECTS
}
Console.WriteLine(prod.ToString());
}
To be honest, this query expression is not entirely useful, given that your subset is identical to that
of the data in the incoming parameter. If you want, you could use this incoming parameter to extract
only the Name values of each car using the following selection syntax:
static void ListProductNames(ProductInfo[] products)
{
// Now get only the names of the products.
Console.WriteLine("Only product names:");
var names = from p in products select p.Name;
}
foreach (var n in names)
{
Console.WriteLine("Name: {0}", n);
}
Obtaining Subsets of Data
To obtain a specific subset from a container, you can make use of the where operator. When doing so, the
general template now becomes the following code:
var result = from item in container where BooleanExpression select item;
Notice that the where operator expects an expression that resolves to a Boolean. For example, to
extract from the ProductInfo[] argument only the items that have more than 25 items on hand, you
could author the following code:
stat ic void GetOverstock(ProductInfo[] products)
{
Console.WriteLine("The overstock items!");
// Get only the items where we have more than
// 25 in stock.
var overstock = from p in products where p.NumberInStock > 25 select p;
foreach (ProductInfo c in overstock)
{
Console.WriteLine(c.ToString());
}
}
As seen earlier in this chapter, when you are building a where clause, it is permissible to make use of
any valid C# operators to build complex expressions. For example, recall the query that only extracts out
the BMWs going at least 100 mph:
// Get BMWs going at least 100 mph.
var onlyFastBMWs = from c in myCars
where c.Make == "BMW" && c.Speed >= 100 select c;
460