Sunday, July 17, 2011

ForEach for ICollection<T>

I like inline function list.ForEach() for IList but always disappointed regarding to ICollection. In order to run loop requered to create Enumerator and etc. Therefore I offering short solutions:
public static void ForEach<T>(this IEnumerable<T> collection,Action<T> action)
{
    IEnumerator<T> enumerator = collection.GetEnumerator();
    while (enumerator.MoveNext())
    {
        action.Invoke(enumerator.Current);
    }
}

A using:

Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("a", 123);
dic.Add("b",456);
//Example 1
dic.ForEach(item => Console.WriteLine(item.Key));


Action<string, int> print = (key, value) =>
{
    Console.WriteLine(
        string.Format("Key: {0}, value: {1}", key, value)
    );
};
//Example 2
dic.ForEach(item => print(item.Key, item.Value));

Enjoy.

2 comments:

  1. To make this even more usefull, you should use "this IEnumerable" instead of "this ICollection".

    ReplyDelete