有人可以解释为什么下面的 C# 行与下面的 foeach block 的行为不同吗?
string [] strs = {"asdf", "asd2", "asdf2"};
strs.Select(str => doSomething(str));
foreach(string str in strs){
doSomething(str);
}
我在 doSomething() 中放置了一个断点,它不会在 Select 中触发,但会在 foreach 中触发。
TIA
最佳答案
这是因为 LINQ 查询被延迟了。传递给 Select
方法的 lambda 在您访问结果时实际执行。
尝试:
string [] strs = {"asdf", "asd2", "asdf2"};
var result = strs.Select(str => doSomething(str));
foreach(var item in result) {
}
关于c# - IEnumerable 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7986144/