What is the best way to iterate over a dictionary?

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

    I wrote an extension to loop over a dictionary.

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

    Then you can call

    myDictionary.ForEach((x,y) => Console.WriteLine(x + " - " + y));
    

提交回复
热议问题