How to sort an OrderedDictionary using Linq in C# (using .NET 3.5)?

后端 未结 2 453
悲哀的现实
悲哀的现实 2021-01-17 18:40

I need to sort an OrderedDictionary (System.Collections.Specialized) I have this code:

var od = new System.Collections.Specialized.OrderedDictionary();
od.Ad         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-17 18:59

    Following will give you a sorted dictionary based on your OrderedDictionary.

    var normalOrderedDictionary= od.Cast()
                           .OrderBy(r=> r.Value)
                           .ToDictionary(c=> c.Key, d=> d.Value);
    

    There is one thing though, ToDictionary returned a regular dictionary but the order is maintained in the dictionary for the lookup, as soon as any new item is inserted in the dictionary, they the order cannot be guaranteed. To avoid this, use SortedDictionary which has a constructor that takes a regular dictionary as parameter

    var sortedDictionary = new SortedDictionary(normalOrderedDictionary);
    

    (Make sure to replace string with the correct types for Key and value in the above line).

    Output:

    foreach (var entry in sortedDictionary)
        Console.WriteLine("Key: {0} Value: {1}", entry.Key, entry.Value);
    
    Key: a3 Value: 2
    Key: a1 Value: 3
    Key: a4 Value: 4
    Key: a2 Value: 5
    

提交回复
热议问题