.NET: forEach () extension methods and dictionary
I have a quick question: I am doing a lot of iterations in the Dictionary.Value collections and annoying me that I need to call .ToList () in order to then call .ForEach () as there seems to be none of the enumerated collections in the dictionary (itself dictionary, collection of keys, or collection of values) have an extension method ForEach.
Is there a good reason why the ForEach () extension method was not implemented in these collections, or is it just what MS felt was not important?
Is this unusual for iterating over Dictionary collections? I often use dictionaries rather than lists when storing data retrieved from databases using the Identity value as the key. I have to admit many times when I don't even look for the Id key, but this is just a habit I fell into ...
source to share
Eric Lippert explains why Microsoft didn't write an extension methodForEach
.
You can write it 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;
}
source to share
Hmm, let's update my comment to answer so I can include readable code.
Eric makes a good argument against general ForEach
on IEnumerable<>
, but Dictionary<>
it will still be useful for, because a simple loop ForEach
gives you KeyValuePair
, but a lambda can have two arguments, one for the key and one for the value, which makes the code clearer.
public static void ForEach<TKey, TValue>(this Dictionary<TKey, TValue> dict, Action<TKey, TValue> action) {
if (dict == null) throw new ArgumentNullException("dict");
if (action == null) throw new ArgumentNullException("action");
foreach (KeyValuePair<TKey, TValue> item in dict) {
action(item.Key, item.Value);
}
}
source to share
There is no good reason (IMO) as there was no ForEach extension method implemented in IEnumerable <T> (instead, it's only in List <T>). I created a ForEach extension method in my shared libraries, this is just a few lines of code.
public static void ForEach<T>( this IEnumerable<T> list, Action<T> action ) {
foreach( var o in list ) {
action( o );
}
}
source to share