.NET Tips and Tricks

Blog archive

A For ... Each Extension for LINQ

A lot of the time, when I write a LINQ statement, I follow it with a For ... Each loop that processes each item in the query:

Dim db As New NorthwindModel
Dim ords = From o In db.Orders
           Where o.OrderDate > Date.Now
           Select o

For Each Ord As Order In ords
  '…do something with each selected order
Next

It made sense to me to create an extension method that would (a) attach itself to any LINQ query, and (b) run that For ... Each loop on each item returned from the LINQ query, like this:

Dim db As New NorthwindModel
Dim ords = (From o In db.Orders
            Where o.OrderDate > Date.Now
            Select o).ForEach(Sub (o)
				'…do something with each selected order)

This extension method accepts a lambda expression with the code to execute for each item. I also want my extension method to work with any type of object that comes out of a collection (extension methods automatically deduce the datatype of any collection they're used on). The declaration for my method begins like this:

Public Module PHVExtensions
    <Extension()>
    Public Sub ForEach(Of T)…

The first parameter passed to my method has to be the datatype of the class that I want my method to attach itself to -- in this case, anything that implements the IEnumerable interface. That IEnumerable class (some collection) will be automatically passed to my extension method through this parameter. Extending my declaration to support that gives this code:

Public Module PHVExtensions
    <Extension()>
    Public Sub ForEach(Of T)(coll As IEnumerable(Of T),…

The second parameter passed to my method will be the lambda expression that accepts a single parameter (an item from the collection). Since I'm using a lambda expression that doesn't return a value, I declare that parameter as an Action with its single parameter typed using my placeholder T. Here's the full code for declaring my extension method:

Public Module PHVExtensions
    <Extension()>
    Public Sub ForEach(Of T)(coll As IEnumerable(Of T), 
                               todo As Action(Of T))

    End Sub

End Module

Within my extension method, I simply loop through the collection passed in the first parameter and call the Action passed in the second parameter. As I call the Action, I pass in each item from the collection. The code inside my extension looks like this:

For Each itm As T In coll
  todo(itm)
Next
After doing all this work, I discovered that Igor Ostrovsky had already written this method along with a whole bunch of other useful LINQ extension methods, all in C#. You should check them out. I wish I had before I spent the time writing this code.

Posted by Peter Vogel on 05/31/2013


comments powered by Disqus

Featured

Subscribe on YouTube