.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

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

  • What's New for Python, Java in Visual Studio Code

    Microsoft announced March 2024 updates to its Python and Java extensions for Visual Studio Code, the open source-based, cross-platform code editor that has repeatedly been named the No. 1 tool in major development surveys.

Subscribe on YouTube