views:

285

answers:

4

I have a dictionary in C# like

Dictionary<Person, int>

and I want to sort that dictionary in place with respect to keys (a field in class Person). How can I do it? Every available help on the internet is that of lists with no particular example of in place sorting of Dictionary. Any help would be highly appreciated!

+15  A: 

You can't sort a Dictionary<TKey, TValue> - it's inherently unordered. (Or rather, the order in which entries are retrieved is implementation-specific. You shouldn't rely on it working the same way between versions, as ordering isn't part of its designed functionality.)

You can use SortedList<TKey, TValue> or SortedDictionary<TKey, TValue>, both of which sort by the key (in a configurable way, if you pass an IEqualityComparer<T> into the constructor) - might those be of use to you?

Pay little attention to the word "list" in the name SortedList - it's still a dictionary in that it maps keys to values. It's implemented using a list internally, effectively - so instead of looking up by hash code, it does a binary search. SortedDictionary is similarly based on binary searches, but via a tree instead of a list.

Jon Skeet
+3  A: 

By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.

Scott Dorman
+1  A: 

Try using SortedDictionary

Chris O
+1  A: 

Take a look at SortedDictionary, there's even a constructor overload so you can pass in your own IComparable for the comparisons.

Dave