Linq style "For Each"
Possible Duplicate:
Linq equivalent of foreach for IEnumerable
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);
}
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.
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.
没有任何内置的,但你可以很容易地创建自己的扩展方法来做到这一点:
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);
}
}
链接地址: http://www.djcxy.com/p/52992.html
上一篇: 通过LINQ将函数应用于所有集合元素
下一篇: Linq风格的“For Each”