14

I have a datetime list and I would like to sort it using a lambda expression if possible.

My list:

6/19/1979 8:00:00 AM
5/5/1980 7:00:00 PM
10/20/1982 5:00:00 PM
1/4/1984 6:00:00 AM

The output should be in this order:

1/4/1984 6:00:00 AM 
6/19/1979 8:00:00 AM
10/20/1982 5:00:00 PM
5/5/1980 7:00:00 PM
4

5 回答 5

44

Simply, OrderBy the TimeOfDay:

var list = dateList.OrderBy(x => x.TimeOfDay).ToList(); 
// ToList added in response to comment.
于 2013-08-06T01:47:01.783 回答
7

Above will work only if all the date are same, in case the date are also different you should do the following...

var sortedDates = dates.OrderByDescending(x => x);

or else Don't want to use, or don't know Linq then you can go for following..

static List SortAscending(List list)
{
list.Sort((a, b) => a.CompareTo(b));
return list;
}

static List SortDescending(List list)
{
list.Sort((a, b) => b.CompareTo(a));
return list;
}
于 2013-12-06T11:53:08.710 回答
0
var result=dates.OrderBy(d=>d-d.Date);
于 2013-08-06T01:46:11.193 回答
0

use this solution

list<DateTime> YourList=new  list<DateTime> ();
.
.
.
YourList.OrderByDescending(x=>x.Date).ThenByDescending(x=>x.TimeOfDay).ToList()   
于 2016-04-06T08:53:13.593 回答
0

list.Sort((a, b) => a.CompareTo(b)); Where list is you List variable.

于 2017-04-27T08:00:37.607 回答