Maicon
Maicon

Reputation: 51

Sorting IDictionary Generic

I need to know if there is any way of ordering an IDictionary without knowing what type it is exactly ...

For example, I have a method that received an object and within this I have a Dictionary object ... all I know is that it is a Dictionary so I can do this:

public void MyMethod(PropertyInfo propriedadeParametro, object parameters){
   IDictionary dictionary = ((IDictionary) propriedadeParametro.GetValue (parameters, null));
}

but need sort the items of this Dictionary by EnumPersonalizado regardless of what the other Type "something?" has

Upvotes: 0

Views: 1204

Answers (4)

Robert Byrne
Robert Byrne

Reputation: 560

There are plenty of legitimate reasons to want to apply a partial ordering to dictionaries based on key, it isn't a fundamental quality that keys be unordered, only that a given key will yield a given value.

That being said, if you find yourself with a non-generic IDictionary, it can actually be quite troublesome to 'sort' by key without knowledge of the key type. In my specific scenario, I wanted a function which would transform an IDictionary into another IDictionary where the entries could be enumerated by the ordered keys.

IDictionary ToSortedDictionary(IDictionary dictionary) {
    return new SortedList(dictionary);
}

This will construct a new dictionary instance, such that traversals (foreach) will visit the entries based on the sort order of the keys.

The oddly named SortedList can be found in System.Collections and orders keys using the ÌComparable interface.

Upvotes: 1

user1968030
user1968030

Reputation:

see this question. Dictionaries by themselves don't have an index order. Consider inheriting from the KeyedCollection class instead. It's a merge of a dictionary and an ordinary list, and it's designed to use a member of your items as the key, and have an index order.

Upvotes: 1

Servy
Servy

Reputation: 203829

You can't sort a dictionary. A dictionary, by definition, doesn't have an "order" of the items within it. The items are stored in some mechanism that is beyond your control that is designed to make it as efficient as possible for adding, removing, and searching.

The best that you can do is take all of the items out of the dictionary, put them in some other sort of collection, and then sort that.

As to your particular case, it's not clear to us what the type of the key or the value in the dictionary is, and that would need to be known in order to be able to try to sort the data.

Upvotes: 4

dead_ant
dead_ant

Reputation: 125

IDictionary is IEnumerable, so you can try to do something like new ArrayList(dictionary).Sort(), but it will try to cast members to IComparable, or you can use a Sort overload which accepts an IComparer object. Another way is to use a reflection - first you find actual Keys/Values types and then you create a call to generic OrderBy.

Upvotes: -2

Related Questions