C# hashcode for array of ints

Viewed 27925

I have a class that internally is just an array of integers. Once constructed the array never changes. I'd like to pre-compute a good hashcode so that this class can be very efficiently used as a key in a Dictionary. The length of the array is less than about 30 items, and the integers are between -1000 and 1000 in general.

8 Answers

You can use Linq methods too:

var array = new int[10];
var hashCode = array.Aggregate(0, (a, v) => 
    HashCode.Combine(a, v.GetHashCode()));

I would recommend:

HashCode.Combine(array)

For .NET Core 2.1 / .NET Standard 2.1 / .NET 5 and later.

Related