What is the best way to iterate over a dictionary?

前端 未结 30 2160
我寻月下人不归
我寻月下人不归 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 06:00

    With .NET Framework 4.7 one can use decomposition

    var fruits = new Dictionary();
    ...
    foreach (var (fruit, number) in fruits)
    {
        Console.WriteLine(fruit + ": " + number);
    }
    

    To make this code work on lower C# versions, add System.ValueTuple NuGet package and write somewhere

    public static class MyExtensions
    {
        public static void Deconstruct(this KeyValuePair tuple,
            out T1 key, out T2 value)
        {
            key = tuple.Key;
            value = tuple.Value;
        }
    }
    

提交回复
热议问题