OrderByDescending for orderedDictionary in c#

91 Views Asked by At

I have declared a ordereddictionary . I am trying to sort it according to its values on descending order but found that "ordereddictionary does not contain a definition for OrderByDescending ".

 dic = dic.OrderByDescending(d => d.Value.Count).ToDictionary(x => x.Key, x => x.Value); 

// declaration of dictionary

OrderedDictionary dic = new OrderedDictionary(StringComparer.CurrentCultureIgnoreCase); 

The key field of this dictionary contains string and values contains a list of strings. I am trying to rearrange it according to the number of values each key holds in descending order. Any suggestion on how to do this.

1

There are 1 best solutions below

0
Jon Skeet On

OrderedDictionary is a non-generic collection, whereas LINQ methods (such as OrderByDescending) almost exclusively operate on the generic type IEnumerable<T>.

Note that even if your call compiled, it wouldn't necessarily do what you want - because you're then calling ToDictionary to end up with a Dictionary<,> result... and Dictionary<,> does not guarantee to preserve any kind of order.

If you don't actually need to perform a lookup on the result, you can just create a list of key/value pairs after ordering. We don't currently know whether you need to start with an OrderedDictionary, but you could consider the generic SortedDictionary<,> type instead, which would allow you to use LINQ on it. So you'd have something like:

var source = new SortedDictionary<string, List<string>>(StringComparer.CurrentCultureIgnoreCase);
// Populate the dictionary here

// This is a List<KeyValuePair<string, List<string>>>
var orderedByCount = source
    .OrderByDescending(pair => pair.Value.Count)
    .ToList();