Question

I'm after some information about sorted dictionaries as I've never used them before in any great detail.

From what I've read about them, they sort themselves by the key value placed in them. Is that correct? Also, does the dictionary continually auto sort itself based on the values being read into it?

If so, is there a way in which I can change this so the dictionary sorts itself via values associated with the keys. For example I have a sorted dictionary with the following:

Key: 4  Value: 40 
Key: 1  Value: 290 
Key: 86  Value: 7 

The sorted dictionary would sort it like so:

Key: 1  Value: 290 
Key: 4  Value: 40 
Key: 86  Value: 7 

But what I would like is for it to do the following:

Key: 86  Value: 7 
Key: 4  Value: 40 
Key: 1  Value: 290 

Finally, how I would go about accessing the first and second points of this sorting so that I could assign them to something else?

Was it helpful?

Solution

by default SortedDictionary<TKey, TValue> performs the Sorting based on the Key but not by Value.

but if you want to have the sorting based on the Value you can use LINQ OrderBy() method asbelow:

From MSDN: SortedDictionary

Represents a collection of key/value pairs that are sorted on the key.

Try This:

var SortedByValueDict = dict.OrderBy(item => item.Value);

Complete Code:

class Program
{
static void Main(string[] args)
{
    SortedDictionary<int, int> dict = new SortedDictionary<int, int>();
    dict.Add(4, 40);
    dict.Add(1, 290);
    dict.Add(86, 7);

    Console.WriteLine("Sorted Dictionary Items sorted by Key");
    foreach (var v in dict)
    {
    Console.WriteLine("Key = {0} and Value = {1}", v.Key, v.Value);
    }

    Console.WriteLine("------------------------\n");
    Console.WriteLine("Sorted Dictionary Items sorted by Value");
    var SortedByValueDict = dict.OrderBy(item => item.Value);

    foreach (var v in SortedByValueDict)
    {
    Console.WriteLine("Key = {0} and Value = {1}", v.Key, v.Value);
    }
}
}

Output:

Sorted Dictionary Items sorted by Key
Key = 1 and Value = 290
Key = 4 and Value = 40
Key = 86 and Value = 7
------------------------

Sorted Dictionary Items sorted by Value
Key = 86 and Value = 7
Key = 4 and Value = 40
Key = 1 and Value = 290
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top