【问题标题】:SortedList Desc OrderSortedList Desc 顺序
【发布时间】:2011-10-19 02:31:54
【问题描述】:

我正在使用SortedListdatecolumn 的排序顺序动态排列arraylist 记录,但默认情况下它是按升序排序的。我一直在尝试按降序获取订单,但无法获取。

【问题讨论】:

    标签: c#


    【解决方案1】:

    比较时应将 y 换成 x

    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);
        }
    }
    

    然后是这个

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

    【讨论】:

    • 这是最好的答案。也不错的通用解决方案!
    • 您可以避免使用内置的 Create lambda 创建自己的类:Comparer&lt;DateTime&gt;.Create(((a, b) =&gt; b.CompareTo(a)))
    【解决方案2】:
    Comparer<DateTime>.Create((x, y) => 0 - Comparer<DateTime>.Default.Compare(x, y));
    

    【讨论】:

    • 已经提出了等效的解决方案,尽管只是作为评论,而不是作为答案。但是,您能否写一些文字来解释代码?此外,正如已经指出的,人们可以简单地交换参数 (Compare(b, a)) 而不是从 0 中减去。
    【解决方案3】:

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

    【讨论】:

    • 这个问题的作者是在谈论按降序排列项目而不是阅读它。尽管如此,仍然是一个有价值的答案。
    【解决方案4】:

    没有办法指示 SortedList 按降序进行排序。您必须像这样提供自己的比较器

        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());
        }
    

    【讨论】:

    • 是的,您必须提供自己的比较。还值得注意的是,有一个内置的字符串比较器可以忽略大小写:StringComparer.CurrentCultureIgnoreCase
    • 感谢您的参考,我已经实现了desc中的顺序
    • 只是交换参数的顺序而不是从 0 中减去结果不是更容易吗? IE。 Comparer&lt;DateTime&gt;.Default.Compare(y, x)?
    【解决方案5】:

    只需在默认比较器中交换 a 和 b,即可通过这些便利类和属性访问:

    var desc = Comparer<DateTime>.Create((a, b) => Comparer<DateTime>.Default.Compare(b, a));
    
    var sortedList = new SortedList<DateTime, T>(desc);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 2012-12-14
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      相关资源
      最近更新 更多