Mark
Mark

Reputation: 981

Dictionary with Key of List<T>

I've run into a little problem using List as the key in a Dictionary(). Here is 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
Console.WriteLine(test[a]);

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

I know it errors because the Dictionary is using the reference of the list rather than the contents of the list. It should ideally be using SequenceEquals to determine whether the key exists if TKey is a List.

Any ideas on how to work around this? Is there another Collection I could use? Do I have to just create a new wrapper class, SequenceDictionary?

Upvotes: 3

Views: 194

Answers (2)

Seva Alekseyev
Seva Alekseyev

Reputation: 61396

Either that, or create your own key class that derives from List<double> and implements IComparable.

Upvotes: 2

Servy
Servy

Reputation: 203812

You need to specify a custom comparer for the dictionary. The dictionary constructor takes an overload with an additional IEqualityComparer<List<double>> parameter. Then you just need to create a class with a Compare method that can compare two List<double>s. You'll also need to provide a GetHashCode method using that

The other option would be to find a Key other than a list. Lists don't make great keys for several reasons:

  • You can't quickly compare two lists. The compare method is O(n).
  • You can't quickly compute the hash of a list; you need to use all of the items in the list to build an appropriate hash.
  • If the list changes while it's inside of the dictionary the hashcode will change, and that will break all sorts of stuff. The list needs to be immutable as long as it's a key in the Dictionary.

Upvotes: 4

Related Questions