Why there is no ForEach extension method on IEnume

2018-12-31 18:07发布

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)?

21条回答
刘海飞了
2楼-- · 2018-12-31 18:33

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.

查看更多
看淡一切
3楼-- · 2018-12-31 18:34

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.

查看更多
孤独寂梦人
4楼-- · 2018-12-31 18:38

Most of the LINQ extension methods return results. ForEach does not fit into this pattern as it returns nothing.

查看更多
登录 后发表回答