Reverse Sorted Dictionary in .NET

后端 未结 5 445
广开言路
广开言路 2020-12-01 13:38

Is there any way I can iterate backwards (in reverse) through a SortedDictionary in c#?

Or is there a way to define the SortedDictionary in descending order to begin

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 14:16

    If you're using .NET 3.5, you can use the OrderByDescending extension method:

            var dictionary = new SortedDictionary();
            dictionary.Add(1, "One");
            dictionary.Add(3, "Three");
            dictionary.Add(2, "Two");
            dictionary.Add(4, "Four");
    
    
    
            var q = dictionary.OrderByDescending(kvp => kvp.Key);
            foreach (var item in q)
            {
                Console.WriteLine(item.Key + " , " + item.Value);
            }
    

提交回复
热议问题