views:

89

answers:

3

I need a Dictionary whose key is an array of integers for example Dictionary<int[],string> or

Dictionary<List<int>,string>.

But I am quite surprised that the Equality method and hash code method is not defined for me. Is there any easy way to implement such a structure other than creating my own MyType: List<int> and to define all necessary methods?

+2  A: 

It isn't predefined because it is expensive. If you know your list is short then just implement the obvious overrides. If not, you'll have to come up with some kind of heuristic for at least GetHashCode. Say, GetHashCode of only the first couple of elements xor-ed together with the Length.

Hans Passant
I think a heuristic should include the Length (heavily). For the rest it would depend on the domain, sampling the list could be better than using just the first elements.
Henk Holterman
@Henk, very good point, added.
Hans Passant
Does a sorted list have a different hash than unsorted? There are many many reasons not to provide a default implementation (edit: and make assumptions about container contents) here than pure expense.
Marc
@Marc, right, that's why I mentioned the problem domain. There is no general solution here. Even the Length property could be irrelevant in some (rare) situations.
Henk Holterman
+1  A: 

GetHashCode and Equality are defined for List, they're just not overridden to give you behavior that you might expect and instead.

If you're using .NET 3.5 you can write a extension methods for List that implements an override for both GetHashCode(), and Equality()

Alan
But will the `Dictionary<,>` methods use those extension methods?
strager
A: 

Instead of creating your own type, you could provide two methods somewhere

string ConvertListToString(List<int> l){...};
List<int> ConvertStringToList(string s){...};

and use a Dictionary<string,string> instead.

Doc Brown
Very good if (and only if) the list is fairly short.
Henk Holterman