What is the best way to iterate over a dictionary?

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

    Using C# 7, add this extension method to any project of your solution:

    public static class IDictionaryExtensions
    {
        public static IEnumerable<(TKey, TValue)> Tuples(
            this IDictionary dict)
        {
            foreach (KeyValuePair kvp in dict)
                yield return (kvp.Key, kvp.Value);
        }
    }
    


    And use this simple syntax

    foreach (var(id, value) in dict.Tuples())
    {
        // your code using 'id' and 'value'
    }
    


    Or this one, if you prefer

    foreach ((string id, object value) in dict.Tuples())
    {
        // your code using 'id' and 'value'
    }
    


    In place of the traditional

    foreach (KeyValuePair kvp in dict)
    {
        string id = kvp.Key;
        object value = kvp.Value;
    
        // your code using 'id' and 'value'
    }
    


    The extension method transforms the KeyValuePair of your IDictionary into a strongly typed tuple, allowing you to use this new comfortable syntax.

    It converts -just- the required dictionary entries to tuples, so it does NOT converts the whole dictionary to tuples, so there are no performance concerns related to that.

    There is a only minor cost calling the extension method for creating a tuple in comparison with using the KeyValuePair directly, which should NOT be an issue if you are assigning the KeyValuePair's properties Key and Value to new loop variables anyway.

    In practice, this new syntax suits very well for most cases, except for low-level ultra-high performance scenarios, where you still have the option to simply not use it on that specific spot.

    Check this out: MSDN Blog - New features in C# 7

提交回复
热议问题