Information Technology Reference
In-Depth Information
Even if you did spot where the parameter order was reversed, did you think
that it was an error? The imperative model places so much more empha-
sis on how actions are performed that it's easy to get lost in those actions
and lose the original intent for what actions are being accomplished.
There's one more justification for using query syntax over looping con-
structs: Queries create a more composable API than looping constructs
can provide. Query syntax naturally leads to constructing algorithms as
small blocks of code that perform one operation on a sequence. The
deferred execution model for queries enables developers to compose these
single operations into multiple operations that can be accomplished in
one enumeration of the sequence. Looping constructs cannot be similarly
composed. You must either create interim storage for each step, or create
methods for each combination of operations on a sequence.
That last example shows how this works. The operation combines a filter
(the where clause) with a sort (the orderby clause) and a projection (the
select clause). All of these are accomplished in one enumeration opera-
tion. The imperative version creates an interim storage model and sepa-
rates the sort into a distinct operation.
I've discussed this as query syntax, though you should remember that
every query has a corresponding method call syntax. Sometimes the query
is more natural, and sometimes the method call syntax is more natural. In
the example above, the query syntax is much more readable. Here's the
equivalent method call syntax:
private static IEnumerable < Tuple < int , int >> MethodIndices3()
{
return Enumerable .Range( 0 , 100 ).
SelectMany(x => Enumerable .Range( 0 , 100 ),
(x,y) => Tuple .Create(x,y)).
Where(pt => pt.Item1 + pt.Item2 < 100 ).
OrderByDescending(pt =>
pt.Item1* pt.Item1 + pt.Item2 * pt.Item2);
}
It's a matter of style whether the query or the method call syntax is more
readable. In this instance, I'm convinced the query syntax is clearer. How-
ever, other examples may be different. Furthermore, some methods do not
have equivalent query syntax. Methods such as Take, TakeWhile, Skip,
SkipWhile, Min, and Max require you to use the method syntax at some
 
Search WWH ::




Custom Search