Reverse Sorted Dictionary in .NET

后端 未结 5 459
广开言路
广开言路 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:19

    Briefly create a reversed sorted dictionary in one line.

    var dict = new SortedDictionary(Comparer.Create((x, y) => y.CompareTo(x)));
    

    There's a way to create a IComparer using System.Collections.Generic.Comparer. Just pass a IComparision delegate to its Create method to build a IComparer.

    var dict = new SortedDictionary(
        Comparer.Create(
            delegate(int x, int y)
            {
                return y.CompareTo(x);
            }
        )
    );
    

    You can use a lambda expression/local function/method to replace the delegate if their significance are (TKey, TKey) => int.

提交回复
热议问题