Runtime: Add ForEach() extension method for IEnumerable

Created on 5 Aug 2020  路  7Comments  路  Source: dotnet/runtime

_This issue has been moved from a ticket on Developer Community._


ForEach is an useful method for all sorts of collections but strangely is only present as a direct method of List<T> when it would be useful in all sorts of collections or IEnumerable types. I noticed this when trying to find the method on ObservableCollection<T> (and found it was missing).


Original Comments

Feedback Bot on 4/14/2020, 11:58 PM:

Thank you for taking the time to provide your suggestion. We will do some preliminary checks to make sure we can proceed further. We'll provide an update once the issue has been triaged by the product team.

api-suggestion area-System.Linq

Most helpful comment

I'm not sure much has changed since Eric Lippert's (IMHO) rather convincing explanation.

All 7 comments

I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

Tagging subscribers to this area: @eiriktsarpalis
See info in area-owners.md if you want to be subscribed.

I'm not sure much has changed since Eric Lippert's (IMHO) rather convincing explanation.

The foreach keyword provides a much better way to achieve the same effect. I'd be inclined to close this cc @adamsitnik

My biggest pet peeve is seeing code that does the following:

IEnumerable<T> enumerable = GetSomeEnumerable();
enumerable.ToList().ForEach(c => { /* do something */ });

I think this is one of the worst antipatterns I come across regularly. There's at best a single array allocation (though likely more), plus the delegate, closure, two method calls, the enumerators and the list itself.

At my previous job I wrote an analyzer that designated this pattern as a compiler error. Adding an extension method on IEnumerable smells of the same thing. Please don't do this, let people use foreach.

Tagging subscribers to this area: @eiriktsarpalis, @jeffhandley
See info in area-owners.md if you want to be subscribed.

Closing since the prefered approach is to use the foreach keyword.

Was this page helpful?
0 / 5 - 0 ratings