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