Geeks With Blogs
My Blog geek yapping
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)
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();
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. Posted on Friday, October 2, 2009 4:09 PM Uncategorized | Back to top

Comments on this post: ForEach or ForEachCopyIntoNewList?

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Wes McClure | Powered by: