受到另一个关于缺失Zip函数的问题的启发:
为什么在IEnumerable接口上没有ForEach扩展方法?或在任何地方吗?唯一获得ForEach方法的类是List<>。有什么原因吗,也许是性能?
受到另一个关于缺失Zip函数的问题的启发:
为什么在IEnumerable接口上没有ForEach扩展方法?或在任何地方吗?唯一获得ForEach方法的类是List<>。有什么原因吗,也许是性能?
当前回答
ForEach方法在LINQ之前添加。如果您添加ForEach扩展,由于扩展方法的约束,它将永远不会被用于List实例。我认为没有添加的原因是为了不干扰现有的。
但是,如果您真的错过了这个漂亮的小函数,您可以推出自己的版本
public static void ForEach<T>(
this IEnumerable<T> source,
Action<T> action)
{
foreach (T element in source)
action(element);
}
其他回答
ForEach方法在LINQ之前添加。如果您添加ForEach扩展,由于扩展方法的约束,它将永远不会被用于List实例。我认为没有添加的原因是为了不干扰现有的。
但是,如果您真的错过了这个漂亮的小函数,您可以推出自己的版本
public static void ForEach<T>(
this IEnumerable<T> source,
Action<T> action)
{
foreach (T element in source)
action(element);
}
是我还是List<T>。Foreach几乎被Linq淘汰了。 最初有
foreach(X x in Y)
其中Y必须是IEnumerable (Pre 2.0),并实现GetEnumerator()。 如果您查看生成的MSIL,您可以看到它与
IEnumerator<int> enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
int i = enumerator.Current;
Console.WriteLine(i);
}
(MSIL见http://alski.net/post/0a-for-foreach-forFirst-forLast0a-0a-.aspx)
然后在DotNet2.0中出现了泛型和列表。我一直觉得Foreach是访问者模式的实现(参见Gamma, Helm, Johnson, Vlissides的设计模式)。
当然,在3.5中,我们可以使用Lambda来达到同样的效果,举个例子 http://dotnet-developments.blogs.techtarget.com/2008/09/02/iterators-lambda-and-linq-oh-my/
我为此写了一篇博文: http://blogs.msdn.com/kirillosenkov/archive/2009/01/31/foreach.aspx
如果你想在。net 4.0中看到这个方法,你可以在这里投票: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=279093
请注意,MoreLINQ NuGet提供了您正在寻找的ForEach扩展方法(以及执行委托并产生结果的Pipe方法)。看到的:
https://www.nuget.org/packages/morelinq https://code.google.com/p/morelinq/wiki/OperatorsOverview
你可以这样写扩展方法:
// Possibly call this "Do"
IEnumerable<T> Apply<T> (this IEnumerable<T> source, Action<T> action)
{
foreach (var e in source)
{
action(e);
yield return e;
}
}
Pros
允许链接:
MySequence
.Apply(...)
.Apply(...)
.Apply(...);
Cons
它实际上不会做任何事情,直到你强制迭代。因此,它不应该被称为. foreach()。你可以在结尾写.ToList(),或者你也可以写这个扩展方法:
// possibly call this "Realize"
IEnumerable<T> Done<T> (this IEnumerable<T> source)
{
foreach (var e in source)
{
// do nothing
;
}
return source;
}
这可能与发布的c#库有很大的不同;不熟悉您的扩展方法的读者将不知道如何理解您的代码。