【发布时间】:2011-10-19 02:31:54
【问题描述】:
我正在使用SortedList 以datecolumn 的排序顺序动态排列arraylist 记录,但默认情况下它是按升序排序的。我一直在尝试按降序获取订单,但无法获取。
【问题讨论】:
标签: c#
我正在使用SortedList 以datecolumn 的排序顺序动态排列arraylist 记录,但默认情况下它是按升序排序的。我一直在尝试按降序获取订单,但无法获取。
【问题讨论】:
标签: c#
比较时应将 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>());
【讨论】:
Comparer<DateTime>.Create(((a, b) => b.CompareTo(a)))
Comparer<DateTime>.Create((x, y) => 0 - Comparer<DateTime>.Default.Compare(x, y));
【讨论】:
Compare(b, a)) 而不是从 0 中减去。
您可以只使用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);
}
【讨论】:
没有办法指示 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());
}
【讨论】:
Comparer<DateTime>.Default.Compare(y, x)?
只需在默认比较器中交换 a 和 b,即可通过这些便利类和属性访问:
var desc = Comparer<DateTime>.Create((a, b) => Comparer<DateTime>.Default.Compare(b, a));
var sortedList = new SortedList<DateTime, T>(desc);
【讨论】: