A
A
Alexsbr2017-10-05 20:26:03
C++ / C#
Alexsbr, 2017-10-05 20:26:03

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;
        }

And then I call SequenceEqual to compare the collections (set1 and set2 are our collections with User):
bool result= set1.SequenceEqual(set2, new Comparer());
The question is that when I look in the debug in GetHashCode the program never enters for some reason. All the action takes place in Equals.
The question arises, Why is this method needed? how to use it correctly in this case? Why is it not being used? Can I somehow influence this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Silin, 2017-10-05
@byme

It is needed for hashing collections like Dictionary, HashSet

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question