1

this question is based on a previous post https://stackoverflow.com/a/8425200/737076

The question is how would you sort the Dictionary once created, and all its children, and children's children.

I'm thinking a Comparer, but would like to get some suggestions.

Community
  • 1
  • 1
Vince
  • 165
  • 1
  • 14

3 Answers3

4

A dictionary can not be sorted. There is no index order like a list or array. You can take the keys of the dictionary and sort the keys, however.

List<string> dictionaryKeys = new List<string>(dict.Keys);
dictionaryKeys.Sort();

Then iterate through the list, retrieving the values in order.

for (i = 0; i < dictionaryKeys.Count; i++)
{
    string key = dictionaryKeys[i];
    string value = dict[key];
}

This would be a simulated sort of a dictionary.

In the case of a Dictionary with multiple levels, you would have to iterate through all the levels and do this using some kind of logic.

However, if your goal is a sorted dictionary i'm sure there are better ways to store your information, maybe a List<class_you_created_to_hold_all_the_information> :)

caesay
  • 16,932
  • 15
  • 95
  • 160
  • If the goal is a sorted dictionary, there's no need to reinvent the wheel: use SortedDictionary. – phoog Apr 18 '12 at 04:23
4

You're looking for a SortedDictionary which is implemented as a binary search tree rather than a hashmap. In addition to implementing it the same way you would in your previous question you need to provide a Comparer to describe how to sort your collection.

Dan Busha
  • 3,723
  • 28
  • 36
  • Did not know that existed. +1 for extending my knowledge of the .Net framework. Although it does not look like there is a way to explicitly sort the items (from my glance at the link you provided). Please enlighten me if I am wrong. – caesay Apr 18 '12 at 01:18
  • @caesay you can construct the SortedDictionary with a custom comparer for the key type. The elements are maintained in key order; there's no need to sort them explicitly. If you want to sort the values, you need to do that elsewhere. – phoog Apr 18 '12 at 04:27
  • Hi, I had already converted my class to use a SortedDictionary. What I was more looking for was a good way to handle the multiple layer of children and sorting at each level. Thank you all for the suggestions. – Vince Apr 18 '12 at 16:14
-1

Use SortedDictionary class.

Thiru kumaran
  • 1,262
  • 1
  • 10
  • 10
  • This was already mentioned. Please don't repeat what someone has already posted, unless you have some useful information to add to it. Which you don't, in this case. – caesay Apr 18 '12 at 01:41