Problem
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);
}
Asked by Stefan Steinegger
Solution #1
Your best bet is to use the ToList() extension method:
someValues.ToList().ForEach(x => list.Add(x + 1));
In the BCL, there is no extension method that directly implements ForEach.
Although there is no extension method in the BCL that achieves this, if you install Reactive Extensions to your project, there is an option in the System namespace:
using System.Reactive.Linq;
someValues.ToObservable().Subscribe(x => list.Add(x + 1));
This achieves the same result as using ToList above, but is (in theory) more efficient because the values are streamed straight to the delegate.
Answered by Mark Seemann
Solution #2
Only this exact implementation of the ForEach method is available in the Array and ListT> classes. (It’s worth noting that the former is static.)
I’m not sure if it’s a significant improvement over a foreach statement, but you could develop an extension method to handle all IEnumerableT> objects.
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
action(item);
}
This would allow you to use the same code you provided in your query.
Answered by Noldorin
Solution #3
Although there isn’t anything built-in, you can easily write your own extension way to accomplish this:
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);
}
}
Answered by LukeH
Solution #4
“Because it’s not a functional operation” (i.e., it’s a stateful operation), according to Microsoft.
Couldn’t you come up with anything like this:
list.Select( x => x+1 )
or, if you absolutely must have it in a List:
var someValues = new List<int>( list.Select( x => x+1 ) );
Answered by stusmith
Solution #5
There isn’t a ForEach extension for Linq. If you want to utilize the List class directly, it offers a ForEach function.
For what it’s worth, the standard foreach syntax will produce the desired results and is likely to be easier to read:
foreach (var x in someValues)
{
list.Add(x + 1);
}
If you’re dead set on having a Linq-style extension, go ahead. It’s simple to do this on your own.
public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
{
foreach (var x in @this)
action(x);
}
Answered by dustyburwell
Post is based on https://stackoverflow.com/questions/1509442/linq-style-for-each