LINQ's ForEach doesn't work on IEnumerable<T>

roger's picture

For some reason, LINQ's ForEach extension method doesn't work on IEnumerable<T>; it only works on IList<T>. Easy fix:

public static class EnumerableExtensions
{
    public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
    {
        foreach (var value in values)
        {
            action(value);
        }
    }
}

Comments

so we implement the enumerable interface with Link in such a way

Why would we need to?

Lets say i have a list of rectangle objects i need to enumerate through via foreach. so we implement the enumerable interface with Link in such a way using List<T>.

    public class RectangleStartingPoints<T> : IEnumerable<T>
    {

        List<T> _items = new List<T>();

        public void Add(T item)
        {
            _items.Add(item);
            
        }

        public IEnumerator<T> GetEnumerator()
        {
            foreach (T item in _items)
            {
                yield return item;
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

    }

since we've implemented using List<T> we can foreach all we want. or maybe i missed something?

Yeah, you did

This isn't about implementing the collection. It's about doing something with it. It's the difference between:

foreach (var user in users.Where(x=>x.Name == "Roger"))
    drinks.Invite(user);

...and...

users.Where(x=>x.Name == "Roger").ForEach(user => drinks.Invite(user));

Admittedly, it's not a huge difference, and Eric Lippert doesn't like it, but it does come in useful for some things.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.