C# Paradigms: Side effects on Lists

前端 未结 6 1713
隐瞒了意图╮
隐瞒了意图╮ 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 should break that up into two blocks of code, one for the retrieval and one for setting the value:

    var nonStopFlights = fResults.Where(f => f.NonStop);
    
    foreach(var flight in nonStopFlights)
        flight.Description = "Fly Direct!";
    

    Or, if you really hate the look of foreach you could try:

    var nonStopFlights = fResults.Where(f => f.NonStop).ToList();
    
    // ForEach is a method on List that is acceptable to make modifications inside.
    nonStopFlights.ForEach(f => f.Description = "Fly Direct!");
    

提交回复
热议问题