What is the best way to iterate over a dictionary?

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

    in addition to the highest ranking posts where there is a discussion between using

    foreach(KeyValuePair entry in myDictionary)
    {
        // do something with entry.Value or entry.Key
    }
    

    or

    foreach(var entry in myDictionary)
    {
        // do something with entry.Value or entry.Key
    }
    

    most complete is the following because you can see the dictionary type from the initialization, kvp is KeyValuePair

    var myDictionary = new Dictionary(x);//fill dictionary with x
    
    foreach(var kvp in myDictionary)//iterate over dictionary
    {
        // do something with kvp.Value or kvp.Key
    }
    

提交回复
热议问题