C# Compare two dictionaries for equality

后端 未结 10 1079
独厮守ぢ
独厮守ぢ 2020-12-01 10:41

I want to compare in C# two dictionaries with as keys a string and as value a list of ints. I assume two dictionaries to be equal when they both ha

10条回答
  •  情歌与酒
    2020-12-01 11:34

    I know this question already has an accepted answer, but I'd like to offer an even simpler alternative:

    using System.Linq;
    using System.Collections.Generic;
    
    namespace Foo
    {
        public static class DictionaryExtensionMethods
        {
            public static bool ContentEquals(this Dictionary dictionary, Dictionary otherDictionary)
            {
                return (otherDictionary ?? new Dictionary())
                    .OrderBy(kvp => kvp.Key)
                    .SequenceEqual((dictionary ?? new Dictionary())
                                       .OrderBy(kvp => kvp.Key));
            }
        }
    }
    

提交回复
热议问题