ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Sort

Sort Dictionary by Key or Value, Ascending/descending

Source

public static void Sort<TKey, TValue>(this Dictionary<TKey, TValue> dict, bool byValue = false, bool descending = false)
{
    Dictionary<TKey,TValue> temp;
    if (descending)
    {
        temp = byValue ? dict.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value) : dict.OrderByDescending(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
    }
    else
    {
        temp = byValue ? dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value) : dict.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
    }
    dict.Clear();
    foreach (var pair in temp)
    {
        dict.Add(pair.Key, pair.Value);
    }
}

Example

dict.Sort(); // By Key ascending
dict.Sort(true,true); // By Value descending

Author: lindsoe

Submitted on: 27 feb. 2021

Language: csharp

Type: Dictionary

Views: 3723