C# Linq 问题
LINQ
是否有一个序列运算符,它允许对每个元素执行某些操作,而无需将其投影到新序列?
这可能看起来有点尴尬,但只是让我知道:)
示例:
IEnumerable<IDisposable> x;
x.PERFORM_ACTION_ON_EVERY_ELEMENT(m => m.Dispose());
显然,这可以使用类似的东西来完成:
foreach (var element in x) x.Dispose();
但是如果某些东西确实存在,那就太好了。
Does LINQ
have a sequence operator, which allows to perform some action on every element without projecting it to a new sequence?
This might see a bit awkward, but just for me to know :)
Example:
IEnumerable<IDisposable> x;
x.PERFORM_ACTION_ON_EVERY_ELEMENT(m => m.Dispose());
Obviously, this could be done using something like:
foreach (var element in x) x.Dispose();
But if something actually exists, that would be nice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,它不存在。具体来说,出于您提到的原因:拥有一个行为与所有其他操作员完全不同的操作员似乎很尴尬。
Eric Lippert,C# 编译器开发人员之一有一篇文章
No, it doesn't exist. Specifically for the reason you mention: It seems awkward having a single operator that behaves completely different than all the others.
Eric Lippert, one of the C# Compiler developers has an article about this.
您可以使用此方法:
它返回源,以便您可以根据需要将其传递给另一个扩展方法。或者如果你想无效,你可以稍微改变一下方法。
You can use this method:
It returns the source so you can pass it along to another extension method as needed. Or if you want to be void, you can change the method a little bit.
morelinq 项目有一个
ForEach
运算符。 LINQ 本身没有,因为 LINQ 完全是关于函数式编程的,而ForEach
有副作用。The morelinq project has a
ForEach
operator. LINQ itself doesn't, as LINQ is all about functional programming, andForEach
has side effects.这是对此的类似讨论 对其中的所有对象运行一个方法一个集合
Here is a similar dicussion on this Run a method on all objects within a collection