我的linq select不起作用,我的foreach起作用 [英] My linq select does not work, my foreach does
本文介绍了我的linq select不起作用,我的foreach起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下不起作用的LINQ Select
.
I have the following LINQ Select
which does not work.
Data.Select(d => d.Value.IsDirty = true); //-- Not working
我的解决方法更长.
foreach (var d in Data)
d.Value.IsDirty = true;
为什么我的第一个代码不起作用?
Why does my first code not work?
推荐答案
Select()
返回一个IEnumerable<…>
,该IEnumerable<…>
具有功能可以遍历输入并调用有问题的代码,但是除非您以某种方式枚举,否则实际上不会这样做:
Select()
returns an IEnumerable<…>
, which has the ability to iterate over the input and invoke the code in question, but doesn't actually do so until you enumerate it in some manner:
Data.Select(d => d.Value.IsDirty = true).ToList();
或
foreach (var _ in Data.Select(d => d.Value.IsDirty = true))
; // Do nothing
但是,考虑到它们会产生副作用(显然是在这里的意图),以上两种都是不好的业力.不要使用它们.原始的foreach
是唯一明智的选择.
However, given that they perform side effects (obviously the intent here), both of the above are bad karma. Don't use them. Your original foreach
is the only sensible choice.
这篇关于我的linq select不起作用,我的foreach起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文