Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an OrderedDictionary using Linq in C# (using .NET 3.5)?

Tags:

c#

.net

linq

I need to sort an OrderedDictionary (System.Collections.Specialized) I have this code:

var od = new System.Collections.Specialized.OrderedDictionary();
od.Add("a1", 3);
od.Add("a2", 5);
od.Add("a3", 2);
od.Add("a4", 4);

I wish to sort it using values. Can I do it using Linq?

like image 975
Lala Trivedi Avatar asked Dec 12 '12 06:12

Lala Trivedi


2 Answers

Following will give you a sorted dictionary based on your OrderedDictionary.

var normalOrderedDictionary= od.Cast<DictionaryEntry>()
                       .OrderBy(r=> r.Value)
                       .ToDictionary(c=> c.Key, d=> d.Value);

There is one thing though, ToDictionary returned a regular dictionary but the order is maintained in the dictionary for the lookup, as soon as any new item is inserted in the dictionary, they the order cannot be guaranteed. To avoid this, use SortedDictionary<TKey,TValue> which has a constructor that takes a regular dictionary as parameter

var sortedDictionary = new SortedDictionary<string, string>(normalOrderedDictionary);

(Make sure to replace string with the correct types for Key and value in the above line).

Output:

foreach (var entry in sortedDictionary)
    Console.WriteLine("Key: {0} Value: {1}", entry.Key, entry.Value);

Key: a3 Value: 2
Key: a1 Value: 3
Key: a4 Value: 4
Key: a2 Value: 5
like image 99
Habib Avatar answered Nov 16 '22 01:11

Habib


You can enumerate over the values/entries by the value easily. You'll just have to cast to the appropriate type in order to activate the linq features.

var sortedOrder = od.Values
    .Cast<int>()        // this is an enumeration of ints
    .OrderBy(i => i);;  // enumerate through ordered by the value

foreach (var item in sortedOrder)
{
    // do stuff
}
like image 29
Jeff Mercado Avatar answered Nov 16 '22 01:11

Jeff Mercado