What is the best way to iterate over a dictionary?

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

    I know this is a very old question, but I created some extension methods that might be useful:

        public static void ForEach(this Dictionary d, Action> a)
        {
            foreach (KeyValuePair p in d) { a(p); }
        }
    
        public static void ForEach(this Dictionary.KeyCollection k, Action a)
        {
            foreach (T t in k) { a(t); }
        }
    
        public static void ForEach(this Dictionary.ValueCollection v, Action a)
        {
            foreach (U u in v) { a(u); }
        }
    

    This way I can write code like this:

    myDictionary.ForEach(pair => Console.Write($"key: {pair.Key}, value: {pair.Value}"));
    myDictionary.Keys.ForEach(key => Console.Write(key););
    myDictionary.Values.ForEach(value => Console.Write(value););
    

提交回复
热议问题