10.2.2009

ForEach or ForEachCopyIntoNewList?

All of us have desired a ForEach extension method in .Net for a while now, after being spoiled with all the new syntactic sugar with lambdas and linq in c#. We've no doubt all implemented our own, here is the one I use:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
  foreach (var item in source)
  {
    action(item);
  }
}
My only issue with this and the foreach loop itself, is that you cannot modify the original collection with your action. There are plenty of cases where we only have a Remove method on a collection and would like to have a RemoveAll. To get around this issue, we can copy items into a new list and iterate over it. With this we can even remove items from the original collection! However, I am now wondering if this should be the default behavior of a ForEach extension method:

public static void ForEachCopyIntoNewList<T>(this IEnumerable<T> source, Action<T> action)
{
  var items = source.ToList();
  items.ForEach(action);
}
I am wondering what everyone thinks, obviously this has implications for delayed execution / lazy loaded scenarios but with that aside, thoughts? I am also looking for a good name to keep this as an alternative extension method but ForEachCopyIntoNewList is rather icky, so if you have a suggestion please let me know.





comments powered by Disqus