What is the best way to iterate over a dictionary?

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

    If you are trying to use a generic Dictionary in C# like you would use an associative array in another language:

    foreach(var item in myDictionary)
    {
      foo(item.Key);
      bar(item.Value);
    }
    

    Or, if you only need to iterate over the collection of keys, use

    foreach(var item in myDictionary.Keys)
    {
      foo(item);
    }
    

    And lastly, if you're only interested in the values:

    foreach(var item in myDictionary.Values)
    {
      foo(item);
    }
    

    (Take note that the var keyword is an optional C# 3.0 and above feature, you could also use the exact type of your keys/values here)

提交回复
热议问题