C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: The Comparison implementation returns the result of the CompareTo method on the 2 arguments.
ComparisonResult: When we sort a collection of DateTimes, we get them in chronological order. This is due to the comparison functions on DateTime.
C# program that sorts List of DateTimes
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = new List<DateTime>();
list.Add(new DateTime(1980, 5, 5));
list.Add(new DateTime(1982, 10, 20));
list.Add(new DateTime(1984, 1, 4));
list.Add(new DateTime(1979, 6, 19));
Display(SortAscending(list), "SortAscending");
Display(SortDescending(list), "SortDescending");
Display(SortMonthAscending(list), "SortMonthAscending");
Display(SortMonthDescending(list), "SortMonthDescending");
}
static List<DateTime> SortAscending(List<DateTime> list)
{
list.Sort((a, b) => a.CompareTo(b));
return list;
}
static List<DateTime> SortDescending(List<DateTime> list)
{
list.Sort((a, b) => b.CompareTo(a));
return list;
}
static List<DateTime> SortMonthAscending(List<DateTime> list)
{
list.Sort((a, b) => a.Month.CompareTo(b.Month));
return list;
}
static List<DateTime> SortMonthDescending(List<DateTime> list)
{
list.Sort((a, b) => b.Month.CompareTo(a.Month));
return list;
}
static void Display(List<DateTime> list, string message)
{
Console.WriteLine(message);
foreach (var datetime in list)
{
Console.WriteLine(datetime);
}
Console.WriteLine();
}
}
Output
SortAscending
6/19/1979 12:00:00 AM
5/5/1980 12:00:00 AM
10/20/1982 12:00:00 AM
1/4/1984 12:00:00 AM
SortDescending
1/4/1984 12:00:00 AM
10/20/1982 12:00:00 AM
5/5/1980 12:00:00 AM
6/19/1979 12:00:00 AM
SortMonthAscending
1/4/1984 12:00:00 AM
5/5/1980 12:00:00 AM
6/19/1979 12:00:00 AM
10/20/1982 12:00:00 AM
SortMonthDescending
10/20/1982 12:00:00 AM
6/19/1979 12:00:00 AM
5/5/1980 12:00:00 AM
1/4/1984 12:00:00 AM