gpt4 book ai didi

C# Linq问题

转载 作者:太空宇宙 更新时间:2023-11-03 17:27:54 25 4
gpt4 key购买 nike

LINQ 是否有序列运算符,允许对每个元素执行某些操作而不将其投影到新序列?

这可能看起来有点尴尬,但只是为了让我知道 :)

例子:

IEnumerable<IDisposable> x;
x.PERFORM_ACTION_ON_EVERY_ELEMENT(m => m.Dispose());

显然,这可以使用类似的东西来完成:

foreach (var element in x) x.Dispose();

但如果某些东西确实存在,那就太好了。

最佳答案

不,它不存在。特别是出于您提到的原因:拥有一个行为与所有其他人完全不同的运算符(operator)似乎很尴尬。

Eric Lippert,C# 编译器开发人员之一 has an article关于这个。

But we can go a bit deeper here. I am philosophically opposed to providing such a method, for two reasons.

The first reason is that doing so violates the functional programming principles that all the other sequence operators are based upon. Clearly the sole purpose of a call to this method is to cause side effects.

The purpose of an expression is to compute a value, not to cause a side effect. The purpose of a statement is to cause a side effect. The call site of this thing would look an awful lot like an expression (though, admittedly, since the method is void-returning, the expression could only be used in a “statement expression” context.)

It does not sit well with me to make the one and only sequence operator that is only useful for its side effects.

关于C# Linq问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5463622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com