Executing a certain action for all elements in an Enumerable

前端 未结 10 1766
春和景丽
春和景丽 2020-12-14 13:49

I have an Enumerable and am looking for a method that allows me to execute an action for each element, kind of like Select but then for si

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 14:38

    Unfortunately there is no built-in way to do this in the current version of LINQ. The framework team neglected to add a .ForEach extension method. There's a good discussion about this going on right now on the following blog.

    http://blogs.msdn.com/kirillosenkov/archive/2009/01/31/foreach.aspx

    It's rather easy to add one though.

    public static void ForEach(this IEnumerable enumerable, Action action) {
      foreach ( var cur in enumerable ) {
        action(cur);
      }
    }
    

提交回复
热议问题