Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List as Dictionary key

I have a dictionary which is keyed by a List:

private Dictionary<List<custom_obj>, string> Lookup;

I'm trying to use ContainsKey, but it doesn't seem to be working, and I have no idea why. Here is the debug information from my Visual Studio Immediate Window:

?Lookup.Keys.ElementAt(7)[0]
{custom_obj}
    Direction: Down
    SID: 2540
?Lookup.Keys.ElementAt(7)[1]
{custom_obj}
    Direction: Down
    SID: 2550
searchObject[0]
{custom_obj}
    Direction: Down
    SID: 2540
searchObject[1]
{custom_obj}
    Direction: Down
    SID: 2550
?Lookup.ContainsKey(searchObject)
false

In my common sense, that last ContainsKey should be true. Hopefully I've included enough information here... any ideas?

Thanks!

like image 852
Harry Avatar asked Apr 04 '12 23:04

Harry


1 Answers

The List<custom_obj> instance acting as a key is referentially unequal to the instance referred to by searchObject.

If you want the dictionary to use the values in the list instead of referential equality to find matching keys, you must supply an IEqualityComparer in the constructor of the dictionary (since you can't override Equals and GetHashCode in List<T>).

like image 178
Amy B Avatar answered Sep 19 '22 23:09

Amy B