0

I am writing a custom Equals and custom GetHashCode for a custom object. I consider objects to be equal under the following conditions:

public bool Equals(MyObject x, MyObject y)
{
  return x.Id == y.Id &&
    x.Type == y.Type &&
    x.Status == y.Status &&
    x.AnArray.Count == y.AnArray.Count &&
    !(x.AnArray.Except(y.AnArray)).Any();
}

As long as the objects' Id, Type, and Status are equal, and AnArray holds the same set of strings (regardless or order), the objects are equal.

eg. Object A with AnArray of ["a","b","c"] is considered to be equal to ObjectB if B's AnArray is ["b","c","a"] assuming all else being equal.

I am attempting to write a GetHashCode function. Id, Type, and Status are straight forward given that Id is a Guid and Type/Status are int's.

public int GetHashCode(MyObject obj)
{
  HashCode code = default(HashCode);
  code.Add(obj.Id.GetHashCode());
  code.Add(obj.Status.GetHashCode());
  code.Add(obj.Type.GetHashCode());
  return code.ToHashCode();
}

How can I include a hash for the array which would return the same values if the array holds the same items, even if they are in a different order? I have attempted to sort the arrays alphabetically and call their default GetHashCode function, but this returns a different hash:

List<string> foo = new List<string>
{
  "Alpha",
  "Bravo",
  "Charlie"
};

List<string> bar = new List<string>
{
  "Bravo",
  "Charlie",
  "Alpha"
};

Console.WriteLine(foo.GetHashCode()); // returns 58225482
Console.WriteLine((bar.OrderBy(x => x).ToList()).GetHashCode()); // returns 54267293
erli
  • 314
  • 4
  • 13
  • `and AnArray holds the same set of strings` - then you should add a `!` in front of that `(x.AnArray.Except(y.AnArray)).Any()`. And it would still not handle the case where `y.AnArray` contains more elements than `x.AnArray`. – GSerg Sep 29 '21 at 17:33

0 Answers0