Dictionary with integer array as a key

半腔热情 提交于 2020-01-20 07:30:25

问题


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?


回答1:


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.




回答2:


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()




回答3:


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.



来源:https://stackoverflow.com/questions/3383534/dictionary-with-integer-array-as-a-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!