2012-06-11 7 views
5
// No overrides required .. let CLR take care of equal and hashcode. 
Class Foo {public Name{get; set;} public Address{get; set;}} 

Dictionary<List<Foo>, int> map = new Dictionary<List<Foo>, int>(); 

質問:オブジェクトリストを辞書キーとして使用できますか?

は、このコードは大丈夫に見えますか? Mapのキーとなることを理解しています。Fooはequalsメソッドとhashcodeメソッドをオーバーライドする必要があります。

私はキーのようなオブジェクトのリストはどうですか?リストの場合、平等は何を意味しますか? "オブジェクトが地図の中に失われている"という問題から安全であると定義されたマップですか?

-Karephul

答えて

3
List<int> a = new List<int>(1, 2, 3); 
List<int> b = new List<int>(1, 2, 3); //different instance than a 

Dictionary<List<int>, int>> map = new Dictionary<List<int>, int>>(); 
map.Add(a, a.Sum()); 
int aSum = map[b]; //KeyNotFoundException because this is a different instance. 


HashSet<int> a = new HashSet<int>(1, 2, 3); 
HashSet<int> b = new HashSet<int>(1, 2, 3); //different instance than a 

Dictionary<HashSet<int>, int>> map1 = new Dictionary<HashSet<int>, int>>(); 
map1.Add(a, a.Sum()); 
int aSum = map1[b]; //KeyNotFoundException because this is a different instance. 


HashSet<int> a = new HashSet<int>(1, 2, 3); 
HashSet<int> b = new HashSet<int>(1, 2, 3); //different instance than a 

Dictionary<HashSet<int>, int>> map2 = new Dictionary<HashSet<int>, int>> 
    (HashSet<int>.CreateSetComparer()); //instance comparison not used - equal sets are equal 
map2.Add(a, a.Sum()); 
int aSum = map2[b]; //6 
+0

+1 – karephul

5

あなたがキーとして元List<T>インスタンスを使用している場合にのみ動作します。
同じアイテムの新しいList<T>を作成すると、List<T>Equals()GetHashCode()を上書きしないため、同じキーとして扱われません。

つまり、参照の等価性を使用します。

これを変更したい場合は、IEqualityComparer<List<T>>と書くことができます。

+0

+1です。例の場合は – karephul

0

確かに、あなたはをできたが、それは信じられないほど限定だろう。簡単に言えば、Fooの組み合わせリストは、リスト要素がすべて同じであっても、Fooであっても同じである必要はありません。List<Foo>。したがって、キーが同じかどうかを確認するために、あいまいではない方法で参照を囲むか、複雑なキーマッチ機能を作成する必要があります。

farより良いキータイプを使用する方が良いでしょう。