C# Compare two dictionaries for equality

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

    Most of the answers are iterating the dictionaries multiple times while it should be simple:

        static bool AreEqual(IDictionary thisItems, IDictionary otherItems)
        {
            if (thisItems.Count != otherItems.Count)
            {
                return false;
            }
            var thisKeys = thisItems.Keys;
            foreach (var key in thisKeys)
            {
                if (!(otherItems.TryGetValue(key, out var value) &&
                      string.Equals(thisItems[key], value, StringComparison.OrdinalIgnoreCase)))
                {
                    return false;
                }
            }
            return true;
        }
    

提交回复
热议问题