How To Sort A Dictionary With C#?

In C#, you can sort a dictionary by using the OrderBy method from the Linq namespace. However, since dictionaries in C# are not inherently ordered data structures, you first need to convert the dictionary to a list of key-value pairs and then sort that list based on the key or value.

Here's an example of how you can sort a dictionary by its keys,

using System;
using System.Linq;
using System.Collections.Generic;
class Program {
    static void Main(string[] args) {
        Dictionary < string, int > dict = new Dictionary < string, int > {
            {
                "apple",
                1
            },
            {
                "banana",
                2
            },
            {
                "cherry",
                3
            }
        };
        var sortedDict = dict.OrderBy(pair => pair.Key).ToDictionary(pair => pair.Key, pair => pair.Value);
        foreach(KeyValuePair < string, int > pair in sortedDict) {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }
    }
}

And here's an example of how you can sort a dictionary by its values,

using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> dict = new Dictionary<string, int>
        {
            {"apple", 1},
            {"banana", 2},
            {"cherry", 3}
        };

        var sortedDict = dict.OrderBy(pair => pair.Value).ToDictionary(pair => pair.Key, pair => pair.Value);

        foreach (KeyValuePair<string, int> pair in sortedDict)
        {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }
    }
}


Similar Articles