C# 按时间排序日期时间列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18070517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:13:05  来源:igfitidea点击:

Sort DateTime List by Time

c#listsortingdatetimelambda

提问by user2138160

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

我有一个日期时间列表,如果可能,我想使用 lambda 表达式对其进行排序。

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

采纳答案by Simon Whitehead

Simply, OrderBythe TimeOfDay:

简单地说,OrderByTimeOfDay

var list = dateList.OrderBy(x => x.TimeOfDay).ToList(); 
// ToList added in response to comment.

回答by Robert McKee

var result=dates.OrderBy(d=>d-d.Date);

回答by susant

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..

或者不想使用,或者不知道Linq那么你可以去关注..

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;
}

回答by Bahman Rashidi

use this solution

使用此解决方案

list<DateTime> YourList=new  list<DateTime> ();
.
.
.
YourList.OrderByDescending(x=>x.Date).ThenByDescending(x=>x.TimeOfDay).ToList()   

回答by Dilip Kumar

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

list.Sort((a, b) => a.CompareTo(b));你在哪里 list 变量。