Dictionary with list key <T>

I'm having a little problem using List as a key in a dictionary (). Here's my sample code that illustrates the problem:

Dictionary<List<double>, string> test = new Dictionary<List<double>, string>();
var a = new List<double>() { 1.0 };
var b = new List<double>() { 2.0 };

test.Add(a, "A");
test.Add(b, "B");

// Works because the reference is the same

// KeyNotFoundException
Console.WriteLine(test[new List<double>() { 1.0 }]);


I know these are errors because the Dictionary is using a list link, not the contents of the list. Ideally, you should use SequenceEquals to determine if a key exists if TKey is a List.

Any ideas on how to get around this? Is there any other collection I could use? Should I just create a new wrapper class, SequenceDictionary?


source to share

2 answers

You need to provide a custom matcher for the dictionary. The dictionary constructor performs overloading with an optional parameter IEqualityComparer<List<double>>

. Then you just need to create a class using the Compare method that can compare two List<double>

s. You also need to provide GetHashCode method using

Another option is to find a Key other than the list. Lists don't make great keys for several reasons:

  • You cannot quickly compare two lists. The comparison method is O (n).
  • You cannot quickly compute the hash of a list; you need to use all the elements in the list to create the corresponding hash.
  • If the list changes when it is inside a dictionary, the hashcode will change and that will break all sorts of things. The required list should be immutable as long as it is key in the dictionary.


Either that, or create your own key class that derives from List<double>

and implements IComparable




All Articles