C# Compare two dictionaries for equality

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

    I like this approach because it gives more details when the test fails

        public void AssertSameDictionary(Dictionary expected,Dictionary actual)
        {
            string d1 = "expected";
            string d2 = "actual";
            Dictionary.KeyCollection keys1= expected.Keys;
            Dictionary.KeyCollection keys2= actual.Keys;
            if (actual.Keys.Count > expected.Keys.Count)
            {
                string tmp = d1;
                d1 = d2;
                d2 = tmp;
                Dictionary.KeyCollection tmpkeys = keys1;
                keys1 = keys2;
                keys2 = tmpkeys;
            }
    
            foreach(TKey key in keys1)
            {
                Assert.IsTrue(keys2.Contains(key), $"key '{key}' of {d1} dict was not found in {d2}");
            }
            foreach (TKey key in expected.Keys)
            {
                //already ensured they both have the same keys
                Assert.AreEqual(expected[key], actual[key], $"for key '{key}'");
            }
        }
    

提交回复
热议问题