I am writing a test for my library written in C#. And I want to test whether two list are same if and only if they have same elements(do not require elements in the same order). I try to convert list to hashset and check whether the two hashset are same. But the running result is not what I expected.
Could anyone explain h开发者_C百科ow the hashset contains method works? Does it compare two objects by the objects getHashCode method or equals method? Thanks!
It uses the IEqualityComparer<> that you passed to the HashSet constructor. If you didn't pass one then it uses EqualityComparer<>.Default. Which, if the element type doesn't implement IEquatable<> uses the Equals and GetHashCode methods of the type.
I would guess that your list contains objects that don't override these methods. Use the IEqualityComparer constructor argument to fix.
精彩评论