Reputation: 981
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
Reputation: 61396
Either that, or create your own key class that derives from List<double>
and implements IComparable
.
Upvotes: 2
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:
Upvotes: 4