views:

593

answers:

2

Hello all

I have a quick question: I do alot of iteration of Dictionary.Value collections and in annoys me that I have to call .ToList() to then be able to call .ForEach(), as it seems none of the enumerable collections in a Dictionary (The Dictionary itself, the Keys collection or the Values collection) have a ForEach extension method.

Is there any good reason why the ForEach() extension method has not been implemented on these collections, or is it just something that MS felt was not important?

Is it that unusual to iterate over Dictionary collections? I often use Dictionaries rather than Lists when storing data pulled out of Databases, using the records Identity value as the Key. I have to admit alot of the time I don't even lookup by the Id key, but it is just a habit I have gotten into...

+1  A: 

There is no good reason (IMO) for there not to have been a ForEach extension method implemented on IEnumerable<T> (instead it is only on List<T>). I have created a ForEach extension method in my common libraries, it's only a few lines of code.

public static void ForEach<T>( this IEnumerable<T> list, Action<T> action ) {
    foreach( var o in list ) {
        action( o );
    }
}
Adam Sills
+4  A: 

Eric Lippert explains why Microsoft didn't write a ForEach extension method.

You can write one yourself:

public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action) {
    if (sequence == null) throw new ArgumentNullException("sequence");
    if (action == null) throw new ArgumentNullException("action");
    foreach(T item in sequence) 
        action(item);
}

//Return false to stop the loop
public static void ForEach<T>(this IEnumerable<T> sequence, Func<T, bool> action) {
    if (sequence == null) throw new ArgumentNullException("sequence");
    if (action == null) throw new ArgumentNullException("action");

    foreach(T item in sequence) 
        if (!action(item))
            return;
}
SLaks
Eric's article makes some good points. I hope people read that before they go too crazy using your answer.
patridge