Linq - 是否有 IEnumerable.ForEach我缺少的扩展方法?
可能的重复:
使用 Foreach 子句的 Lambda 表达式...
为什么没有 ForEach 扩展方法在 IEnumerable 接口上?
这看起来很基本。我正在尝试迭代 IEnumerable 的每个对象。看来我必须先将其投射到列表中。是这样吗?在我看来,IEnumerable 上应该有一个扩展方法可以做到这一点。我一直不得不纠正自己的错误,我已经厌倦了。我是否在某个地方错过了它?
myEnumerable.ToList().ForEach(...)
我想这样做:
myEnumerable.ForEach(...)
Possible Duplicates:
Lambda Expression using Foreach Clause…
Why is there not a ForEach extension method on the IEnumerable interface?
This seems pretty basic. I'm trying to iterate over each object of an IEnumerable. It appears that I would have to cast it to a list first. Is that right? It seems to me there should be an extension method on IEnumerable that does this. I keep having to right my own and I'm getting tired of it. Am I missing it somewhere?
myEnumerable.ToList().ForEach(...)
I want to do this:
myEnumerable.ForEach(...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,没有内置的
ForEach
扩展方法。自己动手很容易:但是为什么要麻烦呢?正如 Eric Lippert 在这篇博文中解释的< /a>,标准的
foreach
语句比有副作用的ForEach
方法更具可读性,并且从哲学上更合适:Nope, there isn't a built-in
ForEach
extension method. It's easy enough to roll your own though:But why bother? As Eric Lippert explains in this blog post, the standard
foreach
statement is more readable -- and philosophically more appropriate -- than a side-effectingForEach
method:不,没有。 Eric Lippert 在他的
概括来说,两个主要原因是:
ForEach
违反了所有其他序列运算符所基于的函数式编程原则 - 无副作用。ForEach
方法不会为该语言添加新的表示能力。您可以使用 foreach 语句轻松更清晰地实现相同的效果。No there isn't. Eric Lippert talks about why this feature was omitted in his blog:
As a summary the two main reasons are:
ForEach
violates the functional programming principles that all the other sequence operators are based upon - no side-effects.ForEach
method would add no new representational power to the language. You can easily achieve the same effect more clearly using a foreach statement.不,没有这样的扩展方法。
List
公开了一个名为的真实方法ForEach
(自 .NET 2.0 以来一直存在)。No, there is no such extension method.
List<T>
exposes a real method calledForEach
(which has been there since .NET 2.0).此处对此进行了一些讨论。它没有内置到框架中,但您可以推出自己的扩展方法并以这种方式使用它。据我所知,这可能是你最好的选择。
我也遇到过同样的情况。
There's some talk about it here. It's not build in to the frame work, but you can roll your own extension method and use it that way. This is probably your best bet from what I can tell.
I've been in the same situation.
IEnumerable没有这个扩展方法。
此处阅读 Eric Lippert 的博客其背后的原因。
所以如果你需要它,你必须自己写:)
IEnumerable do not have this extension method.
Read Eric Lippert's blog here for the reasoning behind it.
So if you need it, you will hav eto write it yourself :)