reorder a dictionary alphabetically in csharp

One way to reorder a dictionary alphabetically by its keys is to use LINQ's OrderBy method. Here is an example implementation:

main.cs
var unsortedDict = new Dictionary<string, int>();
unsortedDict.Add("z", 1);
unsortedDict.Add("b", 2);
unsortedDict.Add("a", 3);

var sortedDict = unsortedDict.OrderBy(x => x.Key)
                             .ToDictionary(x => x.Key, x => x.Value);

foreach (var item in sortedDict)
{
    Console.WriteLine(item.Key + ": " + item.Value);
}
340 chars
13 lines

The OrderBy method sorts the dictionary by its keys in ascending order. We then convert the sorted sequence back to a dictionary using the ToDictionary method. Running the above code will output:

main.cs
a: 3
b: 2
z: 1
15 chars
4 lines

Note that while the keys are ordered alphabetically, the values are still associated with their original keys.

gistlibby LogSnag