Executing a certain action for all elements in an Enumerable

前端 未结 10 1765
春和景丽
春和景丽 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:30

    You are looking for the ever-elusive ForEach that currently only exists on the List generic collection. There are many discussions online about whether Microsoft should or should not add this as a LINQ method. Currently, you have to roll your own:

    public static void ForEach(this IEnumerable value, Action action)
    {
      foreach (T item in value)
      {
        action(item);
      }
    }
    

    While the All() method provides similar abilities, it's use-case is for performing a predicate test on every item rather than an action. Of course, it can be persuaded to perform other tasks but this somewhat changes the semantics and would make it harder for others to interpret your code (i.e. is this use of All() for a predicate test or an action?).

提交回复
热议问题