使用 Foreach 语句的 Lambda 表达式
使用 Foreach 语句的 Lambda 表达式
这个问题已经有了答案:
可能是重复问题:
编辑
作为参考,这是Eric在评论中提到的博客文章
https://ericlippert.com/2009/05/18/foreach-vs-foreach/
原始内容
这可能只是一种好奇心,但它适用于C#规范专家...
为什么ForEach()子句不能在IQueryable/IEnumerable结果集上工作(或不可用)...
你必须首先将你的结果转换为ToList()或ToArray()。
可能是C#遍历IEnumerables与List的方式受到技术限制...
是关于IEnumerables/IQuerable集合的延迟执行的问题吗
例如:
var userAgentStrings = uasdc.UserAgentStrings .Where(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));
admin 更改状态以发布 2023年5月21日
完全可以为IEnumerable
编写ForEach
扩展方法。
我不确定为什么它没有作为内置的扩展方法:
- 也许是因为在LINQ之前,
List
和Array
上已经存在ForEach
。 - 也许是因为使用
foreach
循环迭代序列足够简单。 - 也许是因为觉得它不太适用于函数式编程/ LINQ。
- 也许是因为它不可链式调用。(可以很容易地制作可链式版本,然后在执行操作后
yield
返回每个项,但这种行为并不特别直观。)
public static void ForEach(this IEnumerable source, Action action) { if (source == null) throw new ArgumentNullException("source"); if (action == null) throw new ArgumentNullException("action"); foreach (T item in source) { action(item); } }