Comment by klysm

Comment by klysm 3 months ago

7 replies

This isn’t a great example of what linq is good at. There’s no reason to do ToList there, and the ForEach isn’t particularly idiomatic

pjc50 3 months ago

Yeah, I hit the problem that there isn't a null-type equivalent of Select() for Action<T>, nor is there a IEnumerable.ForEach (controversial), so that's a bit of a hack. But I wanted to make it as close to the original example as possible.

bob1029 3 months ago

> There’s no reason to do ToList there

In this case, I would move it to the very end if we are concerned about the underlying data shifting when the collection is actually enumerated.

Forgetting to materialize LINQ results can cause a lot of trouble, oftentimes in ways that happily evade detection while a debugger is attached.

  • klysm 3 months ago

    > if we are concerned about the underlying data shifting when the collection is actually enumerated

    I’m not sure what you mean by this. You can fulfill the IEnumerable contract without allowing multiple enumerations, but that doesn’t really have to do with the data shifting around. Doing ToList can be an expensive and unnecessary allocation

    • bob1029 3 months ago

      Imagine a live SQL query you are subsequently filtering with LINQ.

      • klysm 3 months ago

        Then the ToList will force it to be evaluated on the client - not sure that situation applies

DeathArrow 3 months ago

Yes, ForEach isn't idiomatic but he could use Select instead.

  • klysm 3 months ago

    Side effects in a Select is not idiomatic either