Vince
Vince

Reputation: 165

Sorting a Dictionary<string,Object>, with multiple levels

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.

Upvotes: 1

Views: 1609

Answers (3)

Thiru kumaran
Thiru kumaran

Reputation: 1342

Use SortedDictionary class.

Upvotes: -1

Dan Busha
Dan Busha

Reputation: 3803

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.

Upvotes: 4

caesay
caesay

Reputation: 17233

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

Upvotes: 4

Related Questions