What is the best way to iterate over a dictionary?

前端 未结 30 2362
我寻月下人不归
我寻月下人不归 2020-11-22 05:18

I\'ve seen a few different ways to iterate over a dictionary in C#. Is there a standard way?

30条回答
  •  忘掉有多难
    2020-11-22 05:47

    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}");
    }
    

提交回复
热议问题