C# Compare two dictionaries for equality

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

    The accepted answer above will not always return a correct comparison because using a HashSet to compare 2 lists will not account for duplicate values in the lists. For instance if the OP had:

    var dict1 = new Dictionary>() { { "A", new List() { 1, 2, 1 } } };
    var dict2 = new Dictionary>() { { "A", new List() { 2, 2, 1 } } };
    

    Then the result of the dictionary comparison is they are equal, when they are not. The only solution I see is to sort the 2 list and compare the values by index, but I'm sure someone smarter then me can come up with a more efficient way.

提交回复
热议问题