I'm an amateur programmer, and this seems like a simple problem to fix, but I just can't figure out how.
Below is C# code that isn't acting like I want it to. I expect for this to return 3, yet instead throws a KeyNotFoundException
. The Lists are the same, so shouldn't it be returning 3? Thanks for any help.
Dictionary<object, double> dict = new Dictionary<object, double>();
dict.Add(new List<object>() { "a", "b" }, 3);
double output = dict[new List<object>() { "a", "b" }];
List<T>
is a reference type without a special Equals
implementation. So, in your case, while both of your list instances have the same content, they are still different instances and as such are not considered equal upon key lookup.
Depending on your needs, you could use different solutions:
If you always have the same amount of items in your list, you can use a Tuple:
Dictionary<Tuple<string, string>, double> dict =
new Dictionary<Tuple<string, string>, double>();
dict.Add(Tuple.Create("a", "b"), 3);
double output = dict[Tuple.Create("a", "b")];
If the amount of items differ, you can create your own list that compares its content.