Foreach 与 IEnumerable 上的扩展方法
快速问题,请参阅此代码:
List<int> result = new List<int>();
var list = new List<int> { 1, 2, 3, 4 };
list.Select(value =>
{
result.Add(value);//Does not work??
return value;
});
并且:
result.Count == 0 //true
为什么 result.Add(value) 不执行?
然而这没有执行,另一个问题是有没有办法用扩展方法在IEnumerable上执行foreach?
除了这种方式: IEnumerable.ToList().Foreach(p=>...)
Quick Question, See this code:
List<int> result = new List<int>();
var list = new List<int> { 1, 2, 3, 4 };
list.Select(value =>
{
result.Add(value);//Does not work??
return value;
});
And :
result.Count == 0 //true
Why result.Add(value) not executed?
However this not executed, Another question that is have a way do a foreach on a IEnumerable with Extention Method?
Except this way: IEnumerable.ToList().Foreach(p=>...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为 LINQ 使用延迟执行。在您实际枚举结果(
Select
的返回)之前,委托将不会执行。为了进行演示,请尝试以下操作:
话虽如此,这是一个坏主意。如果可以避免,LINQ 查询就不应该产生副作用。将
Select
视为转换数据的方式,而不是执行代码的方式。您可以编写自己的扩展方法:
但是,我建议不要这样做。有关详细信息,请参阅 Eric Lippert 关于该主题的帖子。
This is because LINQ uses deferred execution. Until you actually enumerate the results (the return of
Select
), the delegates will not execute.To demonstrate, try the following:
That being said, this is a bad idea. LINQ queries should not have side effects if you can avoid it. Think of
Select
as a way to transform your data, not execute code.You could write your own extension method:
However, I would recommend not doing this. For details, refer to Eric Lippert's post on the subject.
Select 是惰性的,并且执行被推迟,直到您开始枚举结果。您需要通过调用 .ToArray 或循环结果来使用结果集:
Select is lazy and the execution is deferred until you start enumerating over the results. You need to consume the resultset by calling .ToArray for example or by looping over the result:
这有效,但全部有效,并将 1 2 3 4 添加到结果中。测试一下。我刚刚做了。
This works but all and adds 1 2 3 4 into result. Test it out. I just did.