CHAPTER 12 LINQ TO OBJECTS
}
// Delegate targets.
public static bool Filter(string game) {return game.Contains(" ");}
public static string ProcessItem(string game) { return game; }
}
You can test this iteration of your string processing logic by calling this method within the Main()
method of the Program class, as follows:
VeryComplexQueryExpression.QueryStringsWithRawDelegates();
If you were to now run the application to test each possible approach, it should not be too
surprising that the output is identical, regardless of the path taken. Keep the following points in mind
regarding how LINQ query expressions are represented under the covers:
•
Query expressions are created using various C# query operators.
•
Query operators are simply shorthand notations for invoking extension methods
defined by the System.Linq.Enumerable type.
•
Many methods of Enumerable require delegates (Func<> in particular) as
parameters.
•
Any method requiring a delegate parameter can instead be passed a lambda
expression.
•
Lambda expressions are simply anonymous methods in disguise (which greatly
improve readability).
•
Anonymous methods are shorthand notations for allocating a raw delegate and
manually building a delegate target method.
Whew! That might have been a bit deeper under the hood than you wanted to have gone, but I hope
this discussion has helped you understand what the user-friendly C# query operators are actually doing
behind the scenes.
Note The LinqUsingEnumerable project can be found under the Chapter 12 subdirectory.
Summary
LINQ is a set of related technologies that attempts to provide a single, symmetrical manner to interact
with diverse forms of data. As explained over the course of this chapter, LINQ can interact with any type
implementing the IEnumerable interface, including simple arrays as well as generic and nongeneric
collections of d ata.
As you have seen, working with LINQ technologies is accomplished using several C# language
features. For example, given the fact that LINQ query expressions can return any number of result sets, it
is common to make use of the var keyword to represent the underlying data type. As well, lambda
expressions, object initialization syntax, and anonymous types can all be used to build very functional
and compact LINQ queries.
470