Dictionary with integer array as a key
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?
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.
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.
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()
精彩评论