How do you sort a dictionary by value?

前端 未结 19 2372
误落风尘
误落风尘 2020-11-22 03:51

I often have to sort a dictionary, consisting of keys & values, by value. For example, I have a hash of words and respective frequencies, that I want to order by frequen

19条回答
  •  一向
    一向 (楼主)
    2020-11-22 04:13

    Actually in C#, dictionaries don't have sort() methods. As you are more interested in sort by values, you can't get values until you provide them key. In short, you need to iterate through them using LINQ's OrderBy(),

    var items = new Dictionary();
    items.Add("cat", 0);
    items.Add("dog", 20);
    items.Add("bear", 100);
    items.Add("lion", 50);
    
    // Call OrderBy() method here on each item and provide them the IDs.
    foreach (var item in items.OrderBy(k => k.Key))
    {
        Console.WriteLine(item);// items are in sorted order
    }
    

    You can do one trick:

    var sortedDictByOrder = items.OrderBy(v => v.Value);
    

    or:

    var sortedKeys = from pair in dictName
                orderby pair.Value ascending
                select pair;
    

    It also depends on what kind of values you are storing: single (like string, int) or multiple (like List, Array, user defined class). If it's single you can make list of it and then apply sort.
    If it's user defined class, then that class must implement IComparable, ClassName: IComparable and override compareTo(ClassName c) as they are more faster and more object oriented than LINQ.

提交回复
热议问题