How to sort items of a SortedDictionary with C#

We can use the OrderBy method to sort a SortedDictionary items. The OrderBy method takes a key name that items will be sorted based on. The following code snippet sorts a SortedDictionary items based on a Key.

 

AuthorList.OrderBy(key => key.Key)

 

The following code snippet sorts a SortedDictionary by keys and by values.

 

public void SortSortedDictionary()

{

    // Create a SortedDictionary with string key and Int16 value pair

    SortedDictionary<string, Int16> AuthorList = new SortedDictionary<string, Int16>();

    AuthorList.Add("Mahesh Chand", 35);

    AuthorList.Add("Mike Gold", 25);

    AuthorList.Add("Praveen Kumar", 29);

    AuthorList.Add("Raj Beniwal", 21);

    AuthorList.Add("Dinesh Beniwal", 84);

 

    // Sorted by Key

    Console.WriteLine("Sorted by Key");

    Console.WriteLine("=============");

    foreach (KeyValuePair<string, Int16> author in AuthorList.OrderBy(key => key.Key))

    {

        Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);

    }

    Console.WriteLine("=============");

    // Sorted by Value

    Console.WriteLine("Sorted by Value");

    Console.WriteLine("=============");

    foreach (KeyValuePair<string, Int16> author in AuthorList.OrderBy(key => key.Value))

    {

        Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);

    }

}

 


Learn more:

Working with SortedDictionary using C#




Similar Articles