lyyzcg
Last Updated: February 25, 2016
·
2.266K
· alexanderbrevig
Feb007acc38e70d57f7b4c205f7e8b26

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);
            }
        }
    }
}
Say Thanks
Respond

2 Responses
Add your response

3111
Ed98676e74b247cc02e5e1e653127350

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

over 1 year ago ·
3112
Feb007acc38e70d57f7b4c205f7e8b26

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

over 1 year ago ·