I\'ve seen a few different ways to iterate over a dictionary in C#. Is there a standard way?
As of C# 7, you can deconstruct objects into variables. I believe this to be the best way to iterate over a dictionary.
Example:
Create an extension method on KeyValuePair that deconstructs it:
public static void Deconstruct(this KeyValuePair pair, out TKey key, out TVal value)
{
key = pair.Key;
value = pair.Value;
}
Iterate over any Dictionary in the following manner
// Dictionary can be of any types, just using 'int' and 'string' as examples.
Dictionary dict = new Dictionary();
// Deconstructor gets called here.
foreach (var (key, value) in dict)
{
Console.WriteLine($"{key} : {value}");
}