Can I use the List of objects as dictionary keys?

// 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>();

Question:

Does this code look good? I understand that in order to be the key on the map, Foo must override the equals and hashcode methods - either override both or none.

I was wondering what is a list of objects as keys? What does equality mean when it comes to the List? Is the card defined above safe from an object-loss-in-map problem?

-Karephul

+5
source share
3 answers
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
+3
source

, List<T> .
List<T> , , List<T> Equals() GetHashCode().

, .

, IEqualityComparer<List<T>>.

+5

Of course you can, but that would be incredibly limited. Simply put, a list of combinations Foo, even if the elements of the list are all the same Foo, is not necessarily the same List<Foo>. Thus, you will need to maintain links not so unambiguously to make sure that the key is the same, or to make a complex function of key mapping.

It would be much better to use a better key type.

0
source

All Articles