I\'ve seen a few different ways to iterate over a dictionary in C#. Is there a standard way?
I know this is a very old question, but I created some extension methods that might be useful:
public static void ForEach(this Dictionary d, Action> a)
{
foreach (KeyValuePair p in d) { a(p); }
}
public static void ForEach(this Dictionary.KeyCollection k, Action a)
{
foreach (T t in k) { a(t); }
}
public static void ForEach(this Dictionary.ValueCollection v, Action a)
{
foreach (U u in v) { a(u); }
}
This way I can write code like this:
myDictionary.ForEach(pair => Console.Write($"key: {pair.Key}, value: {pair.Value}"));
myDictionary.Keys.ForEach(key => Console.Write(key););
myDictionary.Values.ForEach(value => Console.Write(value););