views:

928

answers:

3

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

+2  A: 

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, e.g. Recursion Software

AdamRalph
+2  A: 

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

Jon Skeet
What is such an odd class (that behaves differently depending on ctor) useful for?
configurator
@configurator: A typical optimization for hash tables: move the recently accessed element to the head of its chain; the more frequently accessed an element, the faster it's found. As for behaving differently depending on ctor, think of it as passing a different IComparer to a SortedList.
Vojislav Stojkovic
@Vojislav: This is not "typical optimization". LinkedHashMap doesn't move entries towards beginning in buckets, it just remembers when was each entry used, and moves entry to beginning of 'recently used entries' list. This affects only iteration order, not lookup speed of next searches.
Peter Štibraný
Here is the beauty of LinkedHashMap. It makes a HashMap that is backed by a linked list. If you pass in presorted information, say from a resultSet, then it keeps the information sorted. It can be iterated over in order of insertion and is fast. If I could only ever use one collection, this is it.
WolfmanDragon
A: 
biozinc