Free mag vol1 | Page 517

CHAPTER 12  LINQ TO OBJECTS // Create a query expression targeting the compatible type. var fastCars = from c in myCarsEnum where c.Speed > 55 select c; } foreach (var car in fastCars) { Console.WriteLine("{0} is going too fast!", car.PetName); } Similar to the previous examples, this method, when called from Main() will display only the names “Henry” and “Daisy”, based on the format of our LINQ query. Filtering Data Using OfType() As you know, nongeneric types are capable of containing any combination of items, as the members of these containers (again, such as the ArrayList) are prototyped to receive System.Objects. For example, assume an ArrayList contains a variety of items, only a subset of which are numerical. If you want to obtain a subset that contains only numerical data, you can do so using OfType(), since it filters out each element whose type is different from the given type during the iterations: static void OfTypeAsFilter() { // Extract the ints from the ArrayList. ArrayList myStuff = new ArrayList(); myStuff.AddRange(new object[] { 10, 400, 8, false, new Car(), "string data" }); var myInts = myStuff.OfType(); } // Prints out 10, 400, and 8. foreach (int i in myInts) { Console.WriteLine("Int value: {0}", i); } At this point, you have had a chance to apply LINQ queries to arrays, generic collections, and nongeneric collections. These containers held both C# primitive types (integers, str