Tools: String Manipulations Find Dupes My IP Json Formatter Lorem Ipsum More...
Discussion Options
ajax animation

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

5/17/2018 11:58:02 AM by: CodeLocker

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

View Copy: Content Copied
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);
Copy: Content Copied
ajax animation
×

Get Coding

Store your first code or add more code to your collection.
You must login to report abuse. ×