使用 Foreach 子句的 Lambda 表达式
编辑
作为参考,这里是 eric 在评论中提到的博客文章
https://ericlippert.com/2009/05/18/foreach-vs-foreach/
ORIG
更多的是好奇我想但是 C# 规范专家的一个...
为什么 ForEach() 子句在 IQueryable/IEnumerable 结果集上不起作用(或不可用)...
您必须首先转换结果ToList() 或 ToArray() 与 C# 相比,C# 迭代 IEnumerables 的方式可能存在技术限制。 列表... 这与 IEnumerables/IQuerable 集合的延迟执行有关吗? 例如
var userAgentStrings = uasdc.UserAgentStrings
.Where<UserAgentString>(p => p.DeviceID == 0 &&
!p.UserAgentString1.Contains("msie"));
//WORKS
userAgentStrings.ToList().ForEach(uas => ProcessUserAgentString(uas));
//WORKS
Array.ForEach(userAgentStrings.ToArray(), uas => ProcessUserAgentString(uas));
//Doesn't WORK
userAgentStrings.ForEach(uas => ProcessUserAgentString(uas));
Possible Duplicate:
Why is there not a ForEach extension method on the IEnumerable interface?
EDIT
For reference, here's the blog post which eric referred to in the comments
https://ericlippert.com/2009/05/18/foreach-vs-foreach/
ORIG
More of a curiosity I suppose but one for the C# Specification Savants...
Why is it that the ForEach() clause doesn't work (or isn't available) for use on IQueryable/IEnumerable result sets...
You have to first convert your results ToList() or ToArray()
Presumably theres a technical limitation to the way C# iterates IEnumerables Vs. Lists...
Is it something to do with the Deferred Execution's of IEnumerables/IQuerable Collections.
e.g.
var userAgentStrings = uasdc.UserAgentStrings
.Where<UserAgentString>(p => p.DeviceID == 0 &&
!p.UserAgentString1.Contains("msie"));
//WORKS
userAgentStrings.ToList().ForEach(uas => ProcessUserAgentString(uas));
//WORKS
Array.ForEach(userAgentStrings.ToArray(), uas => ProcessUserAgentString(uas));
//Doesn't WORK
userAgentStrings.ForEach(uas => ProcessUserAgentString(uas));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
完全可以为
IEnumerable
编写ForEach
扩展方法。我不太确定为什么它不作为内置扩展方法包含在内:
ForEach
已经存在于List
和Array< 上/code> 在 LINQ 之前。
foreach
循环来迭代序列非常容易。产生
每个项目的可链接版本很容易,但这种行为并不是特别直观。)It's perfectly possible to write a
ForEach
extension method forIEnumerable<T>
.I'm not really sure why it isn't included as a built-in extension method:
ForEach
already existed onList<T>
andArray
prior to LINQ.foreach
loop to iterate the sequence.yield
s each item after performing an action, but that behaviour isn't particularly intuitive.)