Last Updated: February 25, 2016
·
5.301K
· alexanderbrevig

C# LINQ ForEach that works on IEnumerable<T>

Unfortunately, the BCL does not provide a ForEach that works for IEnumerable. This means that the current solution is to invoke ToList() on the IEnumerable before running ForEach on the list. This is costly both in computation [O(x)] and memory (temp allocated for the list so at some point you have allocated O(x) memory as well).

Here is a file I always include in my projects:
https://gist.github.com/3810761

And for the lazy:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Linq
{
    public static class IEnumerableExtensionForEach
    {
        public static void ForEach<T>(this IEnumerable<T> list, Action<T> block) {
            foreach (var item in list) {
                block(item);
            }
        }
    }
}

2 Responses
Add your response

O(2x) == O(x), since constant coefficients don't affect the complexity class.

over 1 year ago ·

@tomtheisen thanks! That is of course correct. I updated the protip.

over 1 year ago ·