public static void ForEach<T>(this IEnumerable<T> collection,Action<T> action)
{
IEnumerator<T> enumerator = collection.GetEnumerator();
while (enumerator.MoveNext())
{
action.Invoke(enumerator.Current);
}
}
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.
To make this even more usefull, you should use "this IEnumerable" instead of "this ICollection".
ReplyDeleteThank you, you are right.
ReplyDelete