Inspired by another question asking about the missing Zip
function:
Why is there no ForEach
extension method in the Enumerable
class? Or anywhere? The only class that gets a ForEach
method is List<>
. Is there a reason why it's missing (performance)?
To use Foreach, your list should be loaded in primary memory. But due to lazy loading nature of IEnumerable, they doesn't provide ForEach in IEnumerable.
However by eager loading (using ToList()), you can load your list in to memory and take advantage of ForEach.
You can use select when you want to return something. If you don't, you can use ToList first, because you probably don't want to modify anything in the collection.
Most of the LINQ extension methods return results. ForEach does not fit into this pattern as it returns nothing.