C# Compare two dictionaries for equality

后端 未结 10 1039
独厮守ぢ
独厮守ぢ 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:38

    Here is a way using Linq, probably sacrificing some efficiency for tidy code. The other Linq example from jfren484 actually fails the DoesOrderValuesMatter() test, because it depends on the default Equals() for List, which is order-dependent.

    private bool AreDictionariesEqual(Dictionary> dict1, Dictionary> dict2)
    {
        string dict1string = String.Join(",", dict1.OrderBy(kv => kv.Key).Select(kv => kv.Key + ":" + String.Join("|", kv.Value.OrderBy(v => v))));
        string dict2string = String.Join(",", dict2.OrderBy(kv => kv.Key).Select(kv => kv.Key + ":" + String.Join("|", kv.Value.OrderBy(v => v))));
    
        return dict1string.Equals(dict2string);
    }
    

提交回复
热议问题