.net - Linq - 是否有我缺少的 IEnumerable.ForEach<T> 扩展方法?

标签 .net linq .net-4.0 extension-methods

<分区>

Possible Duplicates:
Lambda Expression using Foreach Clause…
Why is there not a ForEach extension method on the IEnumerable interface?

这看起来很基础。我试图遍历 IEnumerable 的每个对象。看来我必须先把它放到一个列表中。是对的吗?在我看来,IEnumerable 上应该有一个扩展方法可以做到这一点。我一直不得不纠正自己的错误,我已经厌倦了。我是不是遗漏了什么地方?

myEnumerable.ToList().ForEach(...)

我想这样做:

myEnumerable.ForEach(...)

最佳答案

不,没有内置的 ForEach 扩展方法。不过自己动手也很容易:

public static class EnumerableExtensions
{
    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);
        }
    }
}

但何必呢?作为Eric Lippert explains in this blog post ,标准的 foreach 语句比有副作用的 ForEach 方法更具可读性——在哲学上也更合适:

myEnumerable.ForEach(x => Console.WriteLine(x));
// vs
foreach (var x in myEnumerable) Console.WriteLine(x);

关于.net - Linq - 是否有我缺少的 IEnumerable.ForEach<T> 扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3873427/

相关文章:

.net - 如何使用 VB.NET 编译 VB.NET 控制台应用程序的源代码

c# - 无法创建常量值。只有原始类型

c# - VS 实体数据模型设计器是否可以配置为使用更新版本的 EF?

c# - Azure 服务总线上的多个客户端接收单独的消息

.net - 如何在 Jenkins 上为 .net 项目设置构建/部署

c# - 'List' 不包含 'Where' 的定义

c# - 使用 cmd shell 合并目录的内容

c# - 匹配所有有效格式 IPv6 地址的正则表达式

.net - 对 csproj 的更改未生效

c# - header 中的 LinqToExcel 点