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