Answer the question
In order to leave comments, you need to log in
How to correctly compare 2 collections for equality using IEqualityComparer?
Question for the connoisseurs. For example I want to compare 2 collections for equality. I use IEqualityComparer for this. It obliges us to implement the Equals and GetHashCode methods.
For example, there are 2 collections of User objects (with fields Name and Age). I will compare them.
To do this, I wrote the following comparator:
public class Comparer : IEqualityComparer<User>
{
public bool Equals(User x, User y)
{
if (x != null && y != null && x.Name == y.Name && x.Age == y.Age)
{
return true;
}
else
{
return false;
}
}
public int GetHashCode(User obj)
{
if (Object.ReferenceEquals(obj, null))
{
return 0;
}
int hashProductName = obj.Name == null ? 0 : obj.Name.GetHashCode();
int hashProductCode = obj.Age.GetHashCode();
return hashProductName ^ hashProductCode;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question