IE枚举选择
有人可以解释为什么以下 C# 行的行为与以下 foeach 块的行为不同吗?
string [] strs = {"asdf", "asd2", "asdf2"};
strs.Select(str => doSomething(str));
foreach(string str in strs){
doSomething(str);
}
我在 doSomething() 内部放置了一个断点,它不会在 Select 中触发,但会在 foreach 中触发。
TIA
Can someone explain why the following line of C# doesn't behave the same as the following foeach block?
string [] strs = {"asdf", "asd2", "asdf2"};
strs.Select(str => doSomething(str));
foreach(string str in strs){
doSomething(str);
}
I put a breakpoint inside of doSomething() and it doesn't fire in the Select but it does with the foreach.
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是因为 LINQ 查询被延迟。当您访问结果时,实际上会执行传递给
Select
方法的 lambda。尝试:
This is because LINQ queries are deferred. The lambda passed to the
Select
method is actually executed when you access the result.Try:
在使用
ToList()
、ToArray()
将Linq
查询转换为Enumarable
之前,不会处理Linq
查询> 等。顺便说一句,相当于您的
foreach
语句是这样的:或
The
Linq
query won't be processed until you convert it to anEnumarable
usingToList()
,ToArray()
, etc.And by the way the equivalent to your
foreach
statement is something like this:or
你需要做类似的事情
you would need to do something like
我认为一旦您使用从 select 返回的值,您就会看到 doSomething() 被调用。查看 yield 了解发生这种情况的原因。
I think once you use the values returned from the select you'll see doSomething() called. Check out yield to see why this is happening.