What is the best way to iterate over a dictionary?

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

    C# 7.0 introduced Deconstructors and if you are using .NET Core 2.0+ Application, the struct KeyValuePair<> already include a Deconstruct() for you. So you can do:

    var dic = new Dictionary() { { 1, "One" }, { 2, "Two" }, { 3, "Three" } };
    foreach (var (key, value) in dic) {
        Console.WriteLine($"Item [{key}] = {value}");
    }
    //Or
    foreach (var (_, value) in dic) {
        Console.WriteLine($"Item [NO_ID] = {value}");
    }
    //Or
    foreach ((int key, string value) in dic) {
        Console.WriteLine($"Item [{key}] = {value}");
    }
    

提交回复
热议问题