252

Is there any Linq style syntax for "For each" operations?

For instance, add values based on one collection to another, already existing one:

IEnumerable<int> someValues = new List<int>() { 1, 2, 3 };

IList<int> list = new List<int>();

someValues.ForEach(x => list.Add(x + 1));

Instead of

foreach(int value in someValues)
{
  list.Add(value + 1);
}
3

6 Answers 6

352

Using the ToList() extension method is your best option:

someValues.ToList().ForEach(x => list.Add(x + 1));

There is no extension method in the BCL that implements ForEach directly.


Although there's no extension method in the BCL that does this, there is still an option in the System namespace... if you add Reactive Extensions to your project:

using System.Reactive.Linq;

someValues.ToObservable().Subscribe(x => list.Add(x + 1));

This has the same end result as the above use of ToList, but is (in theory) more efficient, because it streams the values directly to the delegate.

12
  • 4
    Bear in mind that this isn't ideal for a very long list, as it makes a copy of the entire list before looping through it. Oct 2, 2009 at 13:32
  • 11
    Calling ToList followed by ForEach involves iterating through the original collection twice. I'd prefer a standard foreach loop any day: less typing, more readable and better performance: foreach (var x in someValues) list.Add(x + 1);
    – LukeH
    Oct 2, 2009 at 13:35
  • 54
    For anyone who sees this and thinks its a good answer, its not. It is crazy inefficient. See Noldorin's answer for the correct way to do things.
    – Steve
    Oct 2, 2009 at 14:26
  • 12
    Fair points all, but I'd like to add this: It may be inefficient in theory, but most in-memory lists I work with tend to have less than a dozen items. Perf. problems are usually somewhere else, so I think it is a premature optimization to categorically state that this answer is bad. The question was whether this syntax is available, and this is as close as you get on plain vanilla .NET 3.5 SP1 without writing the extension method yourself. I would love to have a ForEach extension method in the BCL, but it's not available in the current framework. Oct 2, 2009 at 14:42
  • 2
    @Luke: There's no particular benefit, but that wasn't the question either. In any case I think this is a storm in a teacup: in most cases I bet you can't feel the perf diff at all. Oct 2, 2009 at 15:12
126

The Array and List<T> classes already have ForEach methods, though only this specific implementation. (Note that the former is static, by the way).

Not sure it really offers a great advantage over a foreach statement, but you could write an extension method to do the job for all IEnumerable<T> objects.

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach (var item in source)
        action(item);
}

This would allow the exact code you posted in your question to work just as you want.

3
  • 2
    Thanks, It's clear that I could write the extension myself. I just want to use built in stuff as far as possible before doing this. Oct 2, 2009 at 13:28
  • 4
    Yeah, that's fair enough. I also make sure I'm not reinventing BCL functionality too. In this case, there's none however.
    – Noldorin
    Oct 2, 2009 at 13:39
  • 3
    Array class doesn't have a ForEach method :) but there is a "EnumerableExtensions" statşc class in Microsoft.Practices.ObjectBuilder2 namespace. it has foreach method for IEnumerable :) Mar 23, 2016 at 17:15
37

There isn't anything built-in, but you can easily create your own extension method to do it:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null) throw new ArgumentNullException("source");
    if (action == null) throw new ArgumentNullException("action");

    foreach (T item in source)
    {
        action(item);
    }
}
2
  • 4
    Why isn't there anything built in? Am I missing something? This seems like much needed basic functionality. Oct 24, 2018 at 22:50
  • 3
    @DanCsharpster because linq methods aren't supposed to have side effects
    – Casey
    Oct 14, 2020 at 20:16
21

The official MS line is "because it's not a functional operation" (ie it's a stateful operation).

Couldn't you do something like:

list.Select( x => x+1 )

or if you really need it in a List:

var someValues = new List<int>( list.Select( x => x+1 ) );
3
  • 7
    You have a point about functional vs. stateful operations. However, F# was designed as a functional length, and has an equivalent ForEach method.
    – Noldorin
    Oct 2, 2009 at 13:25
  • 1
    Can you give a reference for "The official MS line"? I'm interested in reading the rest of their take.
    – gabe
    Jun 21, 2018 at 22:16
  • 1
    I probably shouldn't have used the word "official", but this is the blog I was thinking of: blogs.msdn.microsoft.com/ericlippert/2009/05/18/…
    – stusmith
    Jul 2, 2018 at 16:14
6

There is no Linq ForEach extension. However, the List class has a ForEach method on it, if you're willing to use the List directly.

For what it's worth, the standard foreach syntax will give you the results you want and it's probably easier to read:

foreach (var x in someValues)
{
    list.Add(x + 1);
}

If you're adamant you want an Linq style extension. it's trivial to implement this yourself.

public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
{
   foreach (var x in @this)
      action(x);
}
4

There isn't anything like that in standard Linq, but there is a ForEach operator in MoreLinq.

Not the answer you're looking for? Browse other questions tagged or ask your own question.