Free mag vol1 | Page 522

CHAPTER 12  LINQ TO OBJECTS } Note that you must use a literal System.Array object and cannot make use of the C# array declaration syntax, given that you don’t know the underlying type of type, as you are operating on a compiler-generated anonymous class! Also note that you are not specifying the type parameter to the generic ToArray() method, as you once again don’t know the underlying data type until compile time, which is too late for your purposes. The obvious problem is that you lose any strong typing, as each item in the Array object is assumed to be of type Object. Nevertheless, when you need to return a LINQ result set that is the result of a projection operation, transforming the data into an Array type (or another suitable container via other members of the Enumerable type) is mandatory. Obtaining Counts Using Enumerable When you are projecting new batches of data, you may need to discover exactly how many items have been returned into the sequence. Any time you need to determine the number of items returned from a LINQ query expression, simply make use of the Count() extension method of the Enumerable class. For example, the following method will find all string objects in a local array that have a length greater than six characters: static void GetCountFromQuery() { string[] currentVideoGames = {"Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2"}; // Get count from the query. int numb = (from g in currentVideoGames where g.Length > 6 select g).Count(); } // Print out the number of items. Console.WriteLine("{0} items honor the LINQ query.", numb); Reversing Result Sets You can reverse the items within a result set quite simply using the Reverse() extension method of the Enumerable class. For example, the following method selects all items from the incoming ProductInfo[] parameter, in reverse: static void ReverseEverything(ProductInfo[] products) { Console.WriteLine("Product in reverse:"); var allProducts = from p in products select p; foreach (var prod in allProducts.Reverse()) { Console.WriteLine(prod.ToString()); } } 462