Possible Duplicates:
Lambda Expression using Foreach Clause…
Why is there not a ForEach extension method on the IEnumerable interface?
这看起来很基础。我试图遍历 IEnumerable 的每个对象。看来我必须先把它放到一个列表中。是对的吗?在我看来,IEnumerable 上应该有一个扩展方法可以做到这一点。我一直不得不纠正自己的错误,我已经厌倦了。我是不是遗漏了什么地方?
myEnumerable.ToList().ForEach(...)
我想这样做:
myEnumerable.ForEach(...)
不,没有内置的 ForEach
扩展方法。不过自己动手也很容易:
public static class EnumerableExtensions
{
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);
}
}
}
但何必呢?作为Eric Lippert explains in this blog post ,标准的 foreach
语句比有副作用的 ForEach
方法更具可读性——在哲学上也更合适:
myEnumerable.ForEach(x => Console.WriteLine(x));
// vs
foreach (var x in myEnumerable) Console.WriteLine(x);