2010-05-25 79 views
5

我可以使用類似數組的C#字典嗎?C#字典的數組

Dictionary<double[],double[]> 

恐怕也不會能夠告訴當數組相等......

編輯:
將在字典中的散列法採取精心呵護陣列?或者只是散列它們的引用?

+2

如果您能滿足我的好奇心,那麼將密鑰設爲數組的業務需求是什麼? – 2010-05-25 20:37:34

+0

我正在收集輸入 - 輸出對(大維度)在分類問題中,其中重複的對在訓練分類器之前以某種方式進行平均... – Betamoo 2010-05-25 20:41:26

回答

5

對於數組鍵,字典將散列和平等的引用,這可能不是你想要的。這給你兩個選擇:實現double[]的包裝類,或者(更好)寫一些實現IEqualityComparer的東西,並將它傳遞給構造函數Dictionary<T, T>

+5

@BlueRaja,做了一個'List '對其內容進行等式比較和散列?我不認爲它確實如此。 – 2010-05-25 20:45:45

3

只有數組引用將被比較。在下面的例子中,字典將具有條目即使數組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]); 
0

我不認爲具有陣列作爲密鑰是一個好主意,尤其是如果它很大,並且您的相等邏輯基於數組的內容。因爲每次你打電話給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>