使用Foreach子句的Lambda表达式

Eoi*_*ell 50 c# foreach lambda .net-3.5

可能重复:
为什么IEnumerable接口上没有ForEach扩展方法?

编辑

作为参考,这里是eric在评论中引用的博客文章

http://blogs.msdn.com/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx

我想更多的好奇心,但C#规范Savants的一个...

为什么ForEach()子句在IQueryable/IEnumerable结果集上不起作用(或不可用)...

你必须首先转换你的结果ToList()或ToArray()大概是对C#迭代IEnumerables Vs的方式的技术限制.列表......是否与IEnumerables/IQuerable Collections的延迟执行有关.例如

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));
Run Code Online (Sandbox Code Playgroud)

Eri*_*ert 57

多么令人惊奇的巧合,我刚才写了一篇关于这个问题的博客文章.它将于 5月18日出版.没有技术原因我们(或你!)无法做到这一点.不是哲学的原因.下周看我的博客,我的论点.

  • @Micah:我在文章中提到的原因尚不清楚?我相信它很有用.我认为保证完成这项工作并不是很有用*,它鼓励不良的编码实践,例如将副作用嵌入到逻辑上看起来像查询的内容中.单独的任何一个原因都足以不添加此方法. (5认同)
  • 我不明白为什么你认为将一堆方法链接在一起时没有用,比如 .Where(...).Select(...).ForEach(...); (2认同)

Luk*_*keH 14

ForEachIEnumerable<T>.编写扩展方法是完全可能的.

我不确定为什么它不作为内置扩展方法包含在内:

  • 也许是因为ForEach已经存在于LINQ之前List<T>Array之前.
  • 也许是因为使用foreach循环迭代序列很容易.
  • 也许是因为感觉不够功能/ LINQy.
  • 也许是因为它不可链接.(yield在执行操作后,很容易制作每个项目的可链接版本,但这种行为并不是特别直观.)

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null) throw new ArgumentNullException("source");
    if (action == null) throw new ArgumentNullException("action");

    foreach (T item in source)
    {
        action(item);
    }
}
Run Code Online (Sandbox Code Playgroud)