.NET: Sort a Dictionary by Key or Value Ascending (OrderBy) or Descending (OrderByDescending)

5/17/2018 3:58:02 PM

Sort .NET Dictionary by Key or Value, either Ascending or Descending. The result is a sorted Dictionary.

var myDictionary = new Dictionary<int, string>()
{
	{ 1, "B" },
	{ 2, "A" },
	{ 3, "C" },
	{ 0, "D" },
};

//ASC by Key
myDictionary = myDictionary.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);

//DESC by Key
myDictionary = myDictionary.OrderByDescending(x => x.Key).ToDictionary(x => x.Key, x => x.Value);

//ASC by Value
myDictionary = myDictionary.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

//DESC by Value
myDictionary = myDictionary.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);