代码之家  ›  专栏  ›  技术社区  ›  Micah

linq-是否缺少ienumerable.foreach<t>扩展方法?[副本]

  •  2
  • Micah  · 技术社区  · 15 年前

    可能重复:
    Lambda Expression using Foreach Clause…
    Why is there not a ForEach extension method on the IEnumerable interface?

    这似乎很基本。我正在尝试迭代IEnumerable的每个对象。看来我得先把它列出来。是吗?在我看来,IEnumerable上应该有一个扩展方法来实现这一点。我一直要自己做,我已经厌倦了。我是不是找不到了?

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

    我想这样做:

    myEnumerable.ForEach(...)
    
    5 回复  |  直到 15 年前
        1
  •  4
  •   LukeH    15 年前

    不,没有内置的 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 陈述比副作用更易读,在哲学上更恰当。 前臂 方法:

    myEnumerable.ForEach(x => Console.WriteLine(x));
    // vs
    foreach (var x in myEnumerable) Console.WriteLine(x);
    
        2
  •  4
  •   Micah    15 年前

    不,没有。埃里克·利珀特谈到为什么在他的 blog :

    很多人问我为什么没有微软提供的foreach序列操作符扩展方法。

    总之,两个主要原因是:

    • 使用 ForEach 违反了所有其他序列运算符基于的函数编程原则-无副作用。
    • 前臂 方法不会给语言增加新的表示能力。使用foreach语句可以更清楚地实现相同的效果。
        3
  •  0
  •   Andrew Hare    15 年前

    不,没有这种扩展方法。 List<T> 显示一个名为 ForEach (自.NET 2.0以来一直存在)。

        4
  •  0
  •   Robert Greiner    15 年前

    有人在谈论它 here . 它不是内置于框架中的,但是您可以滚动自己的扩展方法并以这种方式使用它。据我所知,这可能是你最好的赌注。

    我也遇到过同样的情况。

    public static class Extensions {
      public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {
        foreach (var item in source) {
          action(item);
        }
      }
    }
    
        5
  •  0
  •   Øyvind Bråthen    15 年前

    IEnumerable没有此扩展方法。

    阅读埃里克·利珀特的博客 here 因为背后的原因。

    所以,如果你需要它,你必须自己写:)