Comparing two dictionaries for equal data in c#?

前端 未结 5 1526
小蘑菇
小蘑菇 2021-02-07 09:13

I have two dictionaries containing a string key and then an object. The object contains five fields. Is there an elegant way to ensure both dictionaries first contain the same k

5条回答
  •  梦毁少年i
    2021-02-07 09:52

    The built-in Equals function of Dictionary only checks for reference equality, see this question on SO. Hashcodes do not reliably tell you if two objects are equal; there is always a chance of hash collision. Never use hashcodes as an equality test!

    I would do it by hand: Compare the entry count of both dictionaries, iterate over the key-value-pairs of one dictionary and check if the key exists in the other one and compare the corresponding objects from both dictionaries. Edit: See Rawling's answer :)

提交回复
热议问题