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);
}
}
}
}
Written by Alexander Brevig
Related protips
2 Responses

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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Csharp
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#