What is the best way to iterate over a dictionary?

前端 未结 30 1762
我寻月下人不归
我寻月下人不归 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<string, int>();
    ...
    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<T1, T2>(this KeyValuePair<T1, T2> tuple,
            out T1 key, out T2 value)
        {
            key = tuple.Key;
            value = tuple.Value;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:02
    foreach(KeyValuePair<string, string> entry in myDictionary)
    {
        // do something with entry.Value or entry.Key
    }
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-11-22 06:02

    I would say foreach is the standard way, though it obviously depends on what you're looking for

    foreach(var kvp in my_dictionary) {
      ...
    }
    

    Is that what you're looking for?

    0 讨论(0)
  • 2020-11-22 06:02

    I wrote an extension to loop over a dictionary.

    public static class DictionaryExtension
    {
        public static void ForEach<T1, T2>(this Dictionary<T1, T2> dictionary, Action<T1, T2> action) {
            foreach(KeyValuePair<T1, T2> keyValue in dictionary) {
                action(keyValue.Key, keyValue.Value);
            }
        }
    }
    

    Then you can call

    myDictionary.ForEach((x,y) => Console.WriteLine(x + " - " + y));
    
    0 讨论(0)
  • 2020-11-22 06:04

    I will take the advantage of .NET 4.0+ and provide an updated answer to the originally accepted one:

    foreach(var entry in MyDic)
    {
        // do something with entry.Value or entry.Key
    }
    
    0 讨论(0)
提交回复
热议问题