What is the best way to iterate over a dictionary?

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

    Dictionary< TKey, TValue > It is a generic collection class in c# and it stores the data in the key value format.Key must be unique and it can not be null whereas value can be duplicate and null.As each item in the dictionary is treated as KeyValuePair< TKey, TValue > structure representing a key and its value. and hence we should take the element type KeyValuePair< TKey, TValue> during the iteration of element.Below is the example.

    Dictionary dict = new Dictionary();
    dict.Add(1,"One");
    dict.Add(2,"Two");
    dict.Add(3,"Three");
    
    foreach (KeyValuePair item in dict)
    {
        Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
    }
    

提交回复
热议问题