Search code examples
.netcollectionshashequalityhashcode

.NET combine hash codes insensitive to order


I'm looking for an implementation of hash code to use alongside IReadOnlySet<T>.SetEquals.

.NET's HashCode type appears to be order sensitive, so it is not a good fit.

var random = new Random();
var items = random.GetItems(Enumerable.Range(0, 100).ToArray(), 100);

for (var i = 0; i < 10; i++)
{
    if (i > 0)
    {
        random.Shuffle(items);
    }

    var combined = new HashCode();

    foreach (var item in items)
    {
        combined.Add(item);
    }

    Console.WriteLine("Hash code is {0}", combined.ToHashCode());
}

Hash code is -1745381383
Hash code is 206620979
Hash code is 1544865526
Hash code is 877430619
Hash code is 1668984788
Hash code is 54187377
Hash code is -758239719
Hash code is 1005287804
Hash code is 614467421
Hash code is -954645367

How can I generate the same hash code from components combined in an arbitrary order?


Solution

  • Use HashSet.CreateSetComparer(), which relies on XOR to aggregate the hash codes of the elements.