C# Paradigms: Side effects on Lists

前端 未结 6 1736
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 10:43

I am trying to evolve my understanding of side effects and how they should be controlled and applied.

In the following List of flights, I want to set a property of e

6条回答
  •  渐次进展
    2020-12-29 11:11

    You have two ways of achieving it the LINQ way:

    1. explicit foreach loop

      foreach(Flight f in fResults.Where(flight => flight.NonStop))
        f.Description = "Fly Direct!";
      
    2. with a ForEach operator, made for the side effects:

      fResults.Where(flight => flight.NonStop)
              .ForEach(flight => flight.Description = "Fly Direct!");
      

    The first way is quite heavy for such a simple task, the second way should only be used with very short bodies.

    Now, you might ask yourself why there isn't a ForEach operator in the LINQ stack. It's quite simple - LINQ is supposed to be a functional way of expressing query operations, which especially means that none of the operators are supposed to have side effects. The design team decided against adding a ForEach operator to the stack because the only usage is its side effect.

    A usual implementation of the ForEach operator would be like this:

    public static class EnumerableExtension
    {
      public static void ForEach (this IEnumerable source, Action action)
      {
        if(source == null)
          throw new ArgumentNullException("source");
    
        foreach(T obj in source)
          action(obj);
    
      }
    }
    

提交回复
热议问题