Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Created March 19, 2014 08:47
Show Gist options
  • Save hagbarddenstore/9637845 to your computer and use it in GitHub Desktop.
Save hagbarddenstore/9637845 to your computer and use it in GitHub Desktop.
Sort dates in .NET.
void Main()
{
var dates = new[]
{
new DateTime(2000, 1, 1),
new DateTime(2005, 1, 1),
new DateTime(2010, 1, 1),
new DateTime(2015, 1, 1)
};
Console.WriteLine("Oldest to newest");
dates.OrderBy(x => x)
.Select(x => x.ToString("yyyy-MM-dd"))
.ToList()
.ForEach(Console.WriteLine);
Console.WriteLine();
Console.WriteLine("Newest to oldest");
dates.OrderByDescending(x => x)
.Select(x => x.ToString("yyyy-MM-dd"))
.ToList()
.ForEach(Console.WriteLine);
}
Oldest to newest (OrderBy)
2000-01-01
2005-01-01
2010-01-01
2015-01-01
Newest to oldest (OrderByDescending)
2015-01-01
2010-01-01
2005-01-01
2000-01-01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment