LinkedHashMap in .NET

跟風遠走 提交于 2019-11-26 09:53:15

问题


I wonder if there is a counterpart to java.util.LinkedHashMap in .NET? (ie. the elements are (re)ordered automatically if I access an element. (boolean accessOrder) ).


回答1:


A bit of Googling seems to show that there is no built in C# equivalent for LinkedHashMap, but there are some third party options available.




回答2:


Just to clarify a bit for readers: LinkedHashMap only behaves that way when built with one particular constructor overload. Normally the elements are maintained in insert order. (This feels a little odd to me, but never mind.)

I don't believe there's any such class in .NET. It wouldn't be too hard to build one, using a linked list of elements and a dictionary from key to linked list node. Access would then consist of fetching the linked list node, moving it to the head, and returning the value.

I'd be happy to implement it tonight or tomorrow if you want - although probably not with full unit tests etc. (Fully testing a collection is a time-consuming business!)




回答3:


Here's a C# implementation I found on a forum:

It's undocumented, but does have some tests. It is not generic, however. At least it's something I guess.

@Jon: I'd appreciate it too if you could do a quick implementation. I imagined that a Dictionary on top of a LinkedList would be best, but I hear there are garbage collection issues with LinkedList that slows things down.




回答4:


I used System.Collections.Specialized.OrderedDictionary as a replacement for LinkedHashMap. It worked for me. Is there anything I'm missing about OrderedDictionary (yes, it's not generic, but it is available with .Net 2 or newer)?




回答5:


Nhibernate has a NHibernate.Util.LinkedHashMap implementation.

If you already have it on your code, as I had, it can be handy



来源:https://stackoverflow.com/questions/486948/linkedhashmap-in-net

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