Extending LINQ to allow foreach constructs


Whilst playing around with LINQ over enumerations, I have asked myself whether or not one can extend normal LINQ functionality to also allow a foreach-like construct to form part of the expression itself (very similar to what you would do in jQuery).

Now LINQ results are in the form of IEnumerable instances, and IEnumerable does not supply a ForEach method, yet .NET 3.5 has also given us extension methods… so all we need to do really is to define an extension method like so:

private static void ForEach<T>(this IEnumerable<T> result, Action<T> action){
foreach (T entry in result) action(entry);
}

This will allow us to execute queries of this form:

(from x in [some array] where [some condition involving x]).ForEach([do something with x]);

Not exactly as elegant as fully compliant LINQ syntax, but way better than the alternatives :)

Advertisements

anything to say?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s