Information Technology Reference
In-Depth Information
by extension, the method syntax that implements the query expression
pattern, provides a cleaner expression of your intent than imperative loop-
ing constructs.
This code snippet shows an imperative method of filling an array and then
printing its contents to the Console:
int [] foo = new int [ 100 ];
for ( int num = 0 ; num < foo.Length; num++)
foo[num] = num * num;
foreach ( int i in foo)
Console .WriteLine(i.ToString());
Even this small example focuses too much on how actions are performed
than on what actions are performed. Reworking this small example to use
the query syntax creates more readable code and enables reuse of different
building blocks.
As a first step, you can change the generation of the array to a query result:
int [] foo = ( from n in Enumerable .Range( 0 , 100 )
select n * n).ToArray();
Yo u c a n t h e n d o a s i m i l a r c h a n g e t o t h e s e c o n d l o o p , a l t h o u g h y o u ' l l a l s o
need to write an extension method to perform some action on all the ele-
ments:
foo.ForAll((n) => Console .WriteLine(n.ToString()));
The .NET BCL has a ForAll implementation in List<T>. It's just as sim-
ple to create one for IEnumerable<T>:
public static class Extensions
{
public static void ForAll<T>(
this IEnumerable <T> sequence,
Action <T> action)
{
foreach (T item in sequence)
action(item);
}
}
 
Search WWH ::




Custom Search