Dictionary in C# is a set of keys and values. Sorting dictionary by value can be confusing since there is no straight method provided for the same in either System.Linq or System.Collections.Generic namespace. Let us discuss different ways to sort dictionary by value.
Let us consider below Dictionary
var dictionary = new Dictionary<string, int>();
dictionary.Add("B", 2);
dictionary.Add("A", 1);
dictionary.Add("C", 3);
Using Linq – Method Syntax
//Sort using LINQ method Syntax
var list = dictionary.OrderBy(x => x.Value);
Using Linq – Query Syntax
//Sort using LINQ method Syntax
var list2 = from data in dictionary orderby data.Value
ascending select data;
Converting to List and KeyValuePair using Delegate for .NET Framework 2.0
Since LINQ in not supported in .Net Framework 2.0, so, we can sort dictionary by value by converting it to KeyValuePair and then using a Comparison delegate into the Sort method of System.Collections.Generic namespace
var dictList = new List>(dictionary);
dictList.Sort(
delegate (KeyValuePair<string, int> x,
KeyValuePair<string, int> y)
{
return x.Value.CompareTo(y.Value);
}
);
The Sort method of requires an delegate type Comparison under the System namespace as below
public delegate int Comparison(T x, T y)
Sort Dictionary with Complex Object Type Values
Let us consider below dictionary with object type values
class Bag
{
public int height;
public int length;
public int breadth;
}
static void Main(string[] args)
{
Dictionary<int, Bag> bagDict = new Dictionary<int, Bag>();
bagDict.Add(1, new Bag() { height = 10, length = 20,
breadth = 30 });
bagDict.Add(2, new Bag() { height = 20, length = 20,
breadth = 30 });
bagDict.Add(3, new Bag() { height = 30, length = 20,
breadth = 30 });
}
Now, let’s say that the key is the quantity of the bags and we need to sort the bag dictionary by the “volume” of the bags. We can do it in below ways:
Using LINQ
var sortedBags = bagDict.OrderBy(x => x.Value.length *
x.Value.breadth *
x.Value.height);
Using IComparable Interface
class Bag : IComparable<Bag>
{
public int height;
public int length;
public int breadth;
public int CompareTo([AllowNull] Bag other)
{
return (height * length * breadth)
- (other.height * other.length * other.breadth);
}
}
static void Main(string[] args)
{
// initialize bags here as above
var sortedBagDict = bagDict.ToList();
sortedBagDict.Sort((x, y) => x.Value.CompareTo(y.Value));
}
LINQ has a lot of features other than Sorting. We have written some detailed blog posts regarding LINQ’s Distinct, OrderBy and SingleorDefault and FirstOrDefault.
Key Points
- Dictionary is optimized to save and fetch values, but it is not optimized for sorting.
- To Sort by Keys, we can use SortedDictionary under the System.Collections.Generic namespace.
- When you have to sort by values, a better option is to create a dictionary with your value object as the key. This will simplify the approach.
- Implementation of Dictionary is in hashtable, which is not sortable inherently. Hence dictionary class doesn’t provide any sorting method.
Conclusion
These are the few ways to sort a dictionary in C#. However, in such scenarios, it is preferable to reconsider the data structure in use. If you are known to any other way to implement sorting of dictionary by value, please do mention in the comment box to help our community.