Free mag vol1 | Page 506

CHAPTER 12  LINQ TO OBJECTS static void Main(string[] args) { Console.WriteLine("***** Fun with LINQ to Objects *****\n"); QueryOverStrings(); Console.ReadLine(); } When you have any array of data, it is very common to extract a subset of items based on a given requirement. Maybe you want to obtain only the subitems that contain a number (e.g., System Shock 2, Uncharted 2, and Fallout 3), have more or less than some number of characters, or don’t contain embedded spaces (e .g., Morrowind or Daxter). While you could certainly perform such tasks using members of the System.Array type and a bit of elbow grease, LINQ query expressions can greatly simplify the process. Going on the assumption that you wish to obtain from the array only items that contain an embedded blank space, and you want these items listed in alphabetical order, you could build the following LINQ query expression: static void QueryOverStrings() { // Assume we have an array of strings. string[] currentVideoGames = {"Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2"}; // Build a query expression to find the items in the array // that have an embedded space. IEnumerable subset = from g in currentVideoGames where g.Contains(" ") orderby g select g; } // Print out the results. foreach (string s in subset) Console.WriteLine("Item: {0}", s); Notice that the query expression created here makes use of the from, in, where, orderby, and select LINQ query operators. You will dig into the formalities of query expression syntax later in this chapter. However, even now you should be able to read this statement roughly as “Give me the items inside of currentVideoGames that contain a space, ordered alphabetically.” Here, each item that matches the search criteria has been given the name “g” (as in “game”); however, any valid C# variable name would do: IEnumerable subset = from game in currentVideoGames where game.Contains(" ") orderby game select game; Notice that the returned sequence is held in a variable named subset, typed as a type that implements the generic version of IEnumerable, where T is of type System.String (after all, you are querying an array of strings). After you obtain the result set, you then simply print out each item using a standard foreach construct. If you run your application, you will find the following output: ***** Fun with LINQ to Objects ***** Item: Fallout 3 Item: System Shock 2 446