I am using SortedList
to arrange arraylist
records dynamically in sort order by datecolumn
, but by default it is sorting in ascending
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>());
Comparer<DateTime>.Create((x, y) => 0 - Comparer<DateTime>.Default.Compare(x, y));
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());
}
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);
}