SortedList Desc Order

时间:2011-10-19 02:31:54

标签: c#

我使用SortedListarraylist排序顺序动态排列datecolumn条记录,但默认情况下按升序排序。我一直试图按降序排序,但却无法得到它。

4 个答案:

答案 0 :(得分:30)

在比较

时,应该换x换x
class DescComparer<T> : IComparer<T>
{
    public int Compare(T x, T y)
    {
        return Comparer<T>.Default.Compare(y, x);
    }
}

然后这个

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

答案 1 :(得分: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());
    }

答案 2 :(得分:16)

您可以使用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);
}

答案 3 :(得分:0)

Comparer<DateTime>.Create((x, y) => 0 - Comparer<DateTime>.Default.Compare(x, y));