SortedList Desc Order

Par*_*dha 25 c#

SortedList用于arraylist按排序顺序动态排列记录datecolumn,但默认情况下它按升序排序.我一直试图按降序排序,但却无法得到它.

UBC*_*der 34

在比较时,应该将y换成x

class DescComparer<T> : IComparer<T>
{
    public int Compare(T x, T y)
    {
        return Comparer<T>.Default.Compare(y, x);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后这个

var list = new SortedList<DateTime, string>(new DescComparer<DateTime>());
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案.很好的通用解决方案! (3认同)
  • 您可以使用内置的 Create lambda 来避免创建自己的类:`Comparer&lt;DateTime&gt;.Create(((a, b) =&gt; b.CompareTo(a)))` (2认同)

Pol*_*ity 26

无法指示SortedList按降序排序.你必须像这样提供自己的Comparer

    class DescendedDateComparer : IComparer<DateTime>
    {
        public int Compare(DateTime x, DateTime y)
        {
            // use the default comparer to do the original comparison for datetimes
            int ascendingResult = Comparer<DateTime>.Default.Compare(x, y);

            // turn the result around
            return 0 - ascendingResult;
        }
    }

    static void Main(string[] args)
    {
        SortedList<DateTime, string> test = new SortedList<DateTime, string>(new DescendedDateComparer());
    }
Run Code Online (Sandbox Code Playgroud)

  • 交换参数的顺序而不是从0减去结果是不是更容易?即`Comparer <DateTime> .Default.Compare(y,x)`? (6认同)

Jak*_*ade 19

您可以使用Reverse() 按降序对SortedList进行排序:

var list = new SortedList<DateTime, string>();

list.Add(new DateTime(2000, 1, 2), "Third");
list.Add(new DateTime(2001, 1, 1), "Second");
list.Add(new DateTime(2010, 1, 1), "FIRST!");
list.Add(new DateTime(2000, 1, 1), "Last...");

var desc = list.Reverse();

foreach (var item in desc)
{
    Console.WriteLine(item);
}
Run Code Online (Sandbox Code Playgroud)