SortedList Desc Order

前端 未结 4 655
闹比i
闹比i 2021-01-17 07:09

I am using SortedList to arrange arraylist records dynamically in sort order by datecolumn, but by default it is sorting in ascending

相关标签:
4条回答
  • 2021-01-17 07:53

    Swapping y for x should do when comparing

    class DescComparer<T> : IComparer<T>
    {
        public int Compare(T x, T y)
        {
            if(x == null) return -1;
            if(y == null) return 1;
            return Comparer<T>.Default.Compare(y, x);
        }
    }
    

    and then this

    var list = new SortedList<DateTime, string>(new DescComparer<DateTime>());
    
    0 讨论(0)
  • 2021-01-17 07:55
    Comparer<DateTime>.Create((x, y) => 0 - Comparer<DateTime>.Default.Compare(x, y));
    
    0 讨论(0)
  • 2021-01-17 08:06

    There is no way to instruct the SortedList to do sorting in descended order. You have to provide your own Comparer like this

        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());
        }
    
    0 讨论(0)
  • 2021-01-17 08:13

    You can just use Reverse() to sort the SortedList in descending order:

    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);
    }
    
    0 讨论(0)
提交回复
热议问题