What is the best way to iterate over a dictionary?

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

提交回复
热议问题