C # Array Dictionary

Is it possible to use a C # dictionary for classes like arrays?

Dictionary<double[],double[]>

I am afraid that he will not be able to say when the arrays are equal ...

EDIT:
Will a hash method in a dictionary take good care of arrays? or just hashing their links?

+5
source share
3 answers

For array keys, the dictionary will use hash and equality references, which is probably not what you want. This gives you two options: implement a wrapper class for double[]or (better) write something that implements IEqualityComparerand pass it to the constructor Dictionary<T, T>.

+5
source

. 2 , a b , :

double[] a = new[] { 1.0, 2.1, 3.2 };
double[] b = new[] { 1.0, 2.1, 3.2 };

Dictionary<double[], double[]> d = new Dictionary<double[], double[]>();

d[a] = new [] { 1.1 };
d[b] = new [] { 2.2 };

Console.WriteLine(d.Count);
Console.WriteLine(d[b][0]);
+3

, , . , GetHashCode, , , ...

, , - , , :

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

, Dictionary<ArrayWrapper<double>, ArrayWrapper<double>>. , (, IList<T>)

0

All Articles