LinkedHashMap in .NET

后端 未结 6 1942
天涯浪人
天涯浪人 2020-11-29 09:54

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 accessOr

相关标签:
6条回答
  • 2020-11-29 10:30

    Nhibernate has a NHibernate.Util.LinkedHashMap implementation.

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

    0 讨论(0)
  • 2020-11-29 10:41

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

    0 讨论(0)
  • 2020-11-29 10:50

    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.

    0 讨论(0)
  • 2020-11-29 10:51

    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.

    0 讨论(0)
  • 2020-11-29 10:51

    As there is still no LinkedHashMap in C#, and I needed this functionality, I've implemented one on the latest net core (3.1). https://github.com/idlerboris/LinkedHashMap/blob/master/CustomCollections/CustomCollections/LinkedHashMap.cs. It's covered with basic tests and seems to be good, but feel free to contribute/report issues.

    0 讨论(0)
  • 2020-11-29 10:52

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

    0 讨论(0)
提交回复
热议问题