Linq style "For Each"

463,475

Solution 1

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.

Solution 2

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.

Solution 3

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);
    }
}

Solution 4

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 ) );

Solution 5

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);
}
Share:
463,475

Related videos on Youtube

Stefan Steinegger
Author by

Stefan Steinegger

I create software for a couple of years now. After 10+ years of coding in C# I'm now arrive on Java island. Seen a lot of weird stuff ...

Updated on January 31, 2020

Comments

  • Stefan Steinegger
    Stefan Steinegger almost 4 years

    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);
    }
    
  • Noldorin
    Noldorin about 14 years
    You have a point about functional vs. stateful operations. However, F# was designed as a functional length, and has an equivalent ForEach method.
  • Stefan Steinegger
    Stefan Steinegger about 14 years
    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.
  • Noldorin
    Noldorin about 14 years
    Yeah, that's fair enough. I also make sure I'm not reinventing BCL functionality too. In this case, there's none however.
  • DLL_Whisperer
    DLL_Whisperer over 7 years
    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 :)
  • user3431501
    user3431501 over 5 years
    Can you give a reference for "The official MS line"? I'm interested in reading the rest of their take.
  • stusmith
    stusmith over 5 years
    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/…
  • Dan Csharpster
    Dan Csharpster about 5 years
    Why isn't there anything built in? Am I missing something? This seems like much needed basic functionality.
  • Casey
    Casey about 3 years
    @DanCsharpster because linq methods aren't supposed to have side effects