Free mag vol1 | Page 509

CHAPTER 12  LINQ TO OBJECTS Item: Item: Item: Item: 1 2 3 8 ***** Info about your query ***** resultSet is of type: WhereArrayIterator`1 resultSet location: System.Core Given the fact that the exact underlying type of a LINQ query is certainly not obvious, these first examples have represented the query results as an IEnumerable variable, where T is the type of data in the returned sequence (string, int, etc). However, this is still rather cumbersome. To add insult to injury, given that IEnumerable extends the nongeneric IEnumerable interface, it would also be permissible to capture the result of a LINQ query as follows: System.Collections.IEnumerable subset = from i in numbers where i < 10 select i; Thankfully, implicit typing cleans things up considerably when working with LINQ queries: static void QueryOverInts() { int[] numbers = {10, 20, 30, 40, 1, 2, 3, 8}; // Use implicit typing here... var subset = from i in numbers where i < 10 select i; } // ...and here. foreach (var i in subset) Console.WriteLine("Item: {0} ", i); ReflectOverQueryResults(subset); As a rule of thumb, you will always want to make use of implicit typing when capturing the results of a LINQ query. Just remember, however, that (in a vast majority of cases), the real return value is a type implementing the generic IEnumerable interface. Exactly what this type is under the covers (OrderedEnumerable, WhereArrayIterator, etc) is irrelevant, and not necessary to discover. As seen in the previous code example, you can simply use the var keyword within a foreach construct to iterate over the fetched data. LINQ and Extension Methods Although the current example does not have you author any extension methods directly, you are in fact using them seamlessly in the background. LINQ query expressions can be used to iterate over data containers that implement the generic IEnumerable interface. However, the .NET System.Array class type (used to represent our array of strings and array of integers) does not implement this contract: // The System.Array type does not seem to implement the correct // infrastructure for query expressions! public abstract class Array : ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable 449