按降序排序SortedList C#

Myk*_*lik 2 c# sorting collections

我有

SortedList<string, object> testIds = new SortedList<string, object>();
Run Code Online (Sandbox Code Playgroud)

我把它按降序排列.我用于排序下一个结构:

testIds.ToList().Sort(delegate(KeyValuePair<string, object>x, KeyValuePair<string, object>y)
{
     return x.Key.CompareTo(y.Key)*-1;
});
Run Code Online (Sandbox Code Playgroud)

但它没有帮助我.你能给我一些建议如何解决这个问题?

das*_*ght 8

虽然SortedList<K,V>默认情况下按升序排序,但它提供了一个构造函数,该构造函数采用自定义IComparer<K>,允许您将订单切换到您需要的任何内容.

实现IComparer<string>反转常规比较的结果,并将其提供给以下构造函数SortedList<K,V>:

class ReverseComparer : IComparer<string> {
    public int Compare(string x, string y) {
        return -x.CompareTo(y);
    }
}

var testIds = new SortedList<string,object>(new ReverseComparer());
Run Code Online (Sandbox Code Playgroud)

您可以在一行中编写相同的内容,而无需为其创建命名类:

var testIds = new SortedList<string,object>(
    // Note how the negation is replaced with reversing the order of comparison
    Comparer<string>.Create((x, y) => y.CompareTo(x))
);
Run Code Online (Sandbox Code Playgroud)


dca*_*tro 6

正如 dasblinkenlight 所指出的,您应该使用带有IComparer<T>.

但是,如果这是一次性的事情,最好使用Comparer<T>.Create,而不是为此创建一个全新的类。

var comparer = Comparer<string>.Create((x, y) => y.CompareTo(x)); 

var testIds = new SortedList<string,object>(comparer);
Run Code Online (Sandbox Code Playgroud)

此外,按相反的顺序比较项目时,习惯上是比较y具有x替代比较,xy和反相的结果。