CHAPTER 12 LINQ TO OBJECTS
}
}
Notice that your query expression is grabbing only those items from the List where the Speed
property is greater than 55. If you run the application, you will find that “Henry” and “Daisy” are the only
two items that match the search criteria.
If you want to build a more complex query, you might wish to find only the BMWs that have a Speed
value above 90. To do so, simply build a compound Boolean statement using the C# && operator:
static void GetFastBMWs(List myCars)
{
// Find the fast BMWs!
var fastCars = from c in myCars where c.Speed > 90 && c.Make == "BMW" select c;
foreach (var car in fastCars)
{
Console.WriteLine("{0} is going too fast!", car.PetName);
}
}
In this case, the only pet name printed out is “Henry”.
Applying LINQ Queries to Nongeneric Collections
Recall that the query operators of LINQ are designed to work with any type implementing
IEnumerable (either directly or via extension methods). Given that System.Array has been provided
with such necessary infrastructure, it might surprise you that the legacy (nongeneric) containers within
System.Collections have not. Thankfully, it is still possible to iterate over data contained within
nongeneric collections using the generic Enumerable.OfType() extension method.
The OfType() method is one of the few members of Enumerable that does not extend generic
types. When calling this member off a nongeneric container implementing the IEnumerable interface
(such as the ArrayList), simply specify the type of item within the container to extract a compatible
IEnumerable object. In code, you can store this data point using an implicitly typed variable.
Consider the following new method, which fills an ArrayList with a set of Car objects (be sure to
import the System.Collections namespace into your Program.cs file).
static void LINQOverArrayList()
{
Console.WriteLine("***** LINQ over ArrayList *****");
// Here is a nongeneric collection of cars.
ArrayList myCars = new ArrayList() {
new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"},
new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"},
new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"},
new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"},
new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"}
};
// Transform ArrayList into an IEnumerable-compatible type.
var myCarsEnum = myCars.OfType();
456