Searching for a Generic C# OrderedDictionary?

I’ve spent about half an hour googling for something that could act as key-value Dictionary class, but which, at the same time, could allow access by index. There is, in fact, a misleading-named OrderedDictionary class in the framework (that isn’t sorted, but ordered – in the sense that positioning does matter) that allows access by key and index, but it doesn’t use generics, so it isn’t that powerful.

After browsing some blogs and seeing some implementations I finally found about KeyedCollection. With some effort, it solves my problem, albeit a bit harder than what it could be if we had an OrderedDictionary<TKey, TItem> class. To use it, you need to inherit from it and then implement an abstract method to tell which property of your values is going to be the key.

I was almost going to do that, but then I found this:














This is basically what I was searching for. Instead of inheriting, now all you have to do is instantiate this collection with a lambda expression as a constructor parameter telling the collection who is going to be the key. Something like:

That’s it. Simple, useful, and generic. But I’m still wondering why there is no generic OrderedDictionary in the .net framework, even if there is a non-generic one. I mean, It shouldn’t be that hard.

1 Comment

Leave a Reply to Anonymous Cancel reply

Your email address will not be published. Required fields are marked *