I don't think having an array as the key is a good idea, especially if it's big and if your equality logic is based on the content of the array. Because every time you will call GetHashCode
, it will have to perform calculations on the whole array, which can take some time if the array is big...
A solution would be to wrap the array in a class which would store the hashcode until the data is modified, so that it isn't recomputed every time :
class ArrayWrapper<T>
{
private T[] _array;
public ArrayWrapper(T[] array)
{
_array = array;
}
private int? _hashcode;
public override int GetHashCode()
{
if (!_hashcode.HasValue)
{
_hashcode = ComputeHashCode();
}
return _hashcode.Value;
}
public override bool Equals(object other)
{
// Your equality logic here
}
protected virtual int ComputeHashCode()
{
// Your hashcode logic here
}
public int Length
{
get { return _array.Length; }
}
public T this[int index]
{
get { return _array[index]; }
set
{
_array[index] = value;
// Invalidate the hashcode when data is modified
_hashcode = null;
}
}
}
So your dictionary would be a Dictionary<ArrayWrapper<double>, ArrayWrapper<double>>
. Of course, you might want to add some methods or properties to the wrapper (implement IList<T>
for instance)