Information Technology Reference
In-Depth Information
It may not look that significant, but it can enable more reuse. Anytime you
are performing work on a sequence of elements, ForAll can do the work.
This is a small, simple operation, so you may not see much benefit. In fact,
you're probably right. Let's look at some different problems.
Many operations require you to work through nested loops. Suppose you
need to generate (X,Y) pairs for all integers from 0 through 99. It's obvi-
ous how you would do that with nested loops:
private static IEnumerable < Tuple < int , int >> ProduceIndices()
{
for ( int x = 0 ; x < 100 ; x++)
for ( int y = 0 ; y < 100 ; y++)
yield return Tuple .Create(x, y);
}
Of course, you could produce the same objects with a query:
private static IEnumerable < Tuple < int , int >> QueryIndices()
{
return from x in Enumerable .Range( 0 , 100 )
from y in Enumerable .Range( 0 , 100 )
select Tuple .Create(x, y);
}
They look similar, but the query syntax keeps its simplicity even as the
problem description gets more difficult. Change the problem to generat-
ing only those pairs where the sum of X and Y is less than 100. Compare
these two methods:
private static IEnumerable < Tuple < int , int >> ProduceIndices2()
{
for ( int x = 0 ; x < 100 ; x++)
for ( int y = 0 ; y < 100 ; y++)
if (x + y < 100 )
yield return Tuple .Create(x, y);
}
private static IEnumerable < Tuple < int , int >> QueryIndices2()
{
return from x in Enumerable .Range( 0 , 100 )
from y in Enumerable .Range( 0 , 100 )
 
Search WWH ::




Custom Search