CHAPTER 12 LINQ TO OBJECTS
parameter of this delegate represents the IEnumerable compatible data to process (an array of strings
in this case), while the second type parameter represents the method result data, which is obtained from
a single statement fed into the lambda expression.
The return value of the Where() method is hidden from view in this code example, but under the
covers you are operating on an OrderedEnumerable type. From this object, you call the generic OrderBy()
method, which also requires a Func<> delegate parameter. This time, you are simply passing each item in
turn via a fitting lambda expression. The end result of calling OrderBy() is a new ordered sequence of the
initial data.
Last but not least, you call the Select() method off the sequence returned from OrderBy(), which
results in the final set of data that is sto red in an implicitly typed variable named subset.
To be sure, this “longhand” LINQ query is a bit more complex to tease apart than the previous C#
LINQ query operator example. Part of the complexity is, no doubt, due to the chaining together of calls
using the dot operator. Here is the exact same query, with each step broken into discrete chunks:
static void QueryStringsWithEnumerableAndLambdas2()
{
Console.WriteLine("***** Using Enumerable / Lambda Expressions *****");
string[] currentVideoGames = {"Morrowind", "Uncharted 2",
"Fallout 3", "Daxter", "System Shock 2"};
// Break it down!
var gamesWithSpaces = currentVideoGames.Where(game => game.Contains(" "));
var orderedGames = gamesWithSpaces.OrderBy(game => game);
var subset = orderedGames.Select(game => game);
}
foreach (var game in subset)
Console.WriteLine("Item: {0}", game);
Console.WriteLine();
As you might agree, building a LINQ query expression using the methods of the Enumerable class
directly is much more verbose than making use of the C# query operators. As well, given that the
methods of Enumerable require delegates as parameters, you will typically need to author lambda
expressions to allow the input data to be processed by the underlying delegate target.
Building Query Expressions Using the Enumerable Type and
Anonymous Methods
Given that C# lambda expressions are simply shorthand notations for working with anonymous
methods, consider the third query expression created within the QueryStringsWithAnonymousMethods()
helper function:
static void QueryStringsWithAnonymousMethods()
{
Console.WriteLine("***** Using Anonymous Methods *****");
string[] currentVideoGames = {"Morrowind", "Uncharted 2",
"Fallout 3", "Daxter", "System Shock 2"};
468