Apply function to all elements of collection through LINQ

Midhat picture Midhat · May 5, 2009 · Viewed 182.5k times · Source

I have recently started off with LINQ and its amazing. I was wondering if LINQ would allow me to apply a function - any function - to all the elements of a collection, without using foreach. Something like python lambda functions.

For example if I have a int list, Can I add a constant to every element using LINQ

If i have a DB table, can i set a field for all records using LINQ.

I am using C#

Answer

Jon Skeet picture Jon Skeet · May 5, 2009

A common way to approach this is to add your own ForEach generic method on IEnumerable<T>. Here's the one we've got in MoreLINQ:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    source.ThrowIfNull("source");
    action.ThrowIfNull("action");
    foreach (T element in source)
    {
        action(element);
    }
}

(Where ThrowIfNull is an extension method on any reference type, which does the obvious thing.)

It'll be interesting to see if this is part of .NET 4.0. It goes against the functional style of LINQ, but there's no doubt that a lot of people find it useful.

Once you've got that, you can write things like:

people.Where(person => person.Age < 21)
      .ForEach(person => person.EjectFromBar());