Free mag vol1 | Page 527

CHAPTER 12  LINQ TO OBJECTS The first method, QueryStringsWithOperators(), offers the most straightforward way to build a query expression and is identical to the code seen in the LinqOverArray example found earlier in this chapter: static void QueryStringWithOperators() { Console.WriteLine("***** Using Query Operators *****"); string[] currentVideoGames = {"Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2"}; var subset = from game in currentVideoGames where game.Contains(" ") orderby game select game; } foreach (string s in subset) Console.WriteLine("Item: {0}", s); The obvious benefit of using C# query operators to build query expressions is the fact that the Func<> delegates and calls on the Enumerable type are out of sight and out of mind, as it is the job of the C# compiler to perform this translation. To be sure, building LINQ expressions using various query operators (from, in, where, or orderby) is the most common and straightforward approach. Building Query Expressions Using the Enumerable Type and Lambda Expressions Keep in mind that the LINQ query operators used here are simply shorthand versions for calling various extension methods defined by the Enumerable type. Consider the following QueryStringsWithEnumerableAndLambdas() method, which is processing the local string array now making direct use of the Enumerable extension methods: static void QueryStringsWithEnumerableAndLambdas() { Console.WriteLine("***** Using Enumerable / Lambda Expressions *****"); string[] currentVideoGames = {"Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2"}; // Build a query expression using extension methods // granted to the Array via the Enumerable type. var subset = currentVideoGames.Where(game => game.Contains(" ")) .OrderBy(game => game).Select(game => game); // Print out the results. foreach (var game in subset) Console.WriteLine("Item: {0}", game); Console.WriteLine(); } Here, you begin by calling the Where() extension method on the currentVideoGames string array. Recall that the Array class receives this via an extension method granted by Enumerable. The Enumerable.Where() method requires a System.Func delegate parameter. The first type 467