Free mag vol1 | Page 513

CHAPTER 12  LINQ TO OBJECTS where g.Contains(" ") orderby g select g; } public void PrintGames() { foreach (var item in subset) { Console.WriteLine(item); } } More often than not, LINQ queries are defined within the scope of a method or property. Moreover, to simplify your programming, the variable used to hold the result set will be stored in an implicitly typed local variable using the var keyword. Now, recall from Chapter 3 that implicitly typed variables cannot be used to define parameters, return values, or fields of a class or structure. Given this point, you might wonder exactly how you could return a query result to an external caller. The answer is, it depends. If you have a result set consisting of strongly typed data, such as an array of strings or a List of Cars, you could abandon the use of the var keyword and use a proper IEnumerable or IEnumerable type (again, as IEnumerable extends IEnumerable). Consider the following example for a new Console Application named LinqRetValues: class Program { static void Main(string[] args) { Console.WriteLine("***** LINQ Transformations *****\n"); IEnumerable subset = GetStringSubset(); foreach (string item in subset) { Console.WriteLine(item); } } Console.ReadLine(); static IEnumerable GetStringSubset() { string[] colors = {"Light Red", "Green", "Yellow", "Dark Red", "Red", "Purple"}; // Note subset is an IEnumerable-compatible object. IEnumerable theRedColors = from c in colors where c.Contains("Red") select c; } return theRedColors; } 453