What is the best way to iterate over a dictionary?

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

    The standard way to iterate over a Dictionary, according to official documentation on MSDN is:

    foreach (DictionaryEntry entry in myDictionary)
    {
         //Read entry.Key and entry.Value here
    }
    
    0 讨论(0)
  • 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<int, string> dict = new Dictionary<int, string>();
    dict.Add(1,"One");
    dict.Add(2,"Two");
    dict.Add(3,"Three");
    
    foreach (KeyValuePair<int, string> item in dict)
    {
        Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
    }
    
    0 讨论(0)
  • 2020-11-22 05:38

    In some cases you may need a counter that may be provided by for-loop implementation. For that, LINQ provides ElementAt which enables the following:

    for (int index = 0; index < dictionary.Count; index++) {
      var item = dictionary.ElementAt(index);
      var itemKey = item.Key;
      var itemValue = item.Value;
    }
    
    0 讨论(0)
  • 2020-11-22 05:38

    Generally, asking for "the best way" without a specific context is like asking what is the best color?

    One the one hand, there are many colors and there's no best color. It depends on the need and often on taste, too.

    On the other hand, there are many ways to iterate over a Dictionary in C# and there's no best way. It depends on the need and often on taste, too.

    Most straightforward way

    foreach (var kvp in items)
    {
        // key is kvp.Key
        doStuff(kvp.Value)
    }
    

    If you need only the value (allows to call it item, more readable than kvp.Value).

    foreach (var item in items.Values)
    {
        doStuff(item)
    }
    

    If you need a specific sort order

    Generally, beginners are surprised about order of enumeration of a Dictionary.

    LINQ provides a concise syntax that allows to specify order (and many other things), e.g.:

    foreach (var kvp in items.OrderBy(kvp => kvp.Key))
    {
        // key is kvp.Key
        doStuff(kvp.Value)
    }
    

    Again you might only need the value. LINQ also provides a concise solution to:

    • iterate directly on the value (allows to call it item, more readable than kvp.Value)
    • but sorted by the keys

    Here it is:

    foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
    {
        doStuff(item)
    }
    

    There are many more real-world use case you can do from these examples. If you don't need a specific order, just stick to the "most straightforward way" (see above)!

    0 讨论(0)
  • 2020-11-22 05:38

    As already pointed out on this answer, KeyValuePair<TKey, TValue> implements a Deconstruct method starting on .NET Core 2.0, .NET Standard 2.1 and .NET Framework 5.0 (preview).

    With this, it's possible to iterate through a dictionary in a KeyValuePair agnostic way:

    var dictionary = new Dictionary<int, string>();
    
    // ...
    
    foreach (var (key, value) in dictionary)
    {
        // ...
    }
    
    0 讨论(0)
  • 2020-11-22 05:39

    If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.

    public new IEnumerator<T> GetEnumerator()
    {
       return this.Values.GetEnumerator();
    }
    
    0 讨论(0)
提交回复
热议问题