Comparing two dictionaries for equal data in c#?

前端 未结 5 1519
小蘑菇
小蘑菇 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条回答
  •  爱一瞬间的悲伤
    2021-02-07 09:54

    In this case you can just use the SequenceEquals()-Method, like following:

       Dictionary d1 = new Dictionary();
       d1.Add("first", new { Name = "TestName", Age = 12, ID = 001 }); 
    
       Dictionary d2 = new Dictionary();
       d2.Add("first", new { Name = "TestName", Age = 12, ID = 001 });
    
       Console.WriteLine(d1.SequenceEqual(d2)); //outputs True                
    

    Note: For simplicity i used implicit classes to fill the Dictionaries. The code will work the same way with any objects. The hashcodes of both dictionaries are not equal, which can be easily verified by doing the following:

       Console.WriteLine(d1.GetHashCode() + " " + d2.GetHashCode()); //outputs different hashcodes
    

提交回复
热议问题