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

C# 按时间对日期时间列表排序,c#,list,sorting,datetime,lambda,C#,List,Sorting,Datetime,Lambda,我有一个日期时间列表,如果可能的话,我想使用lambda表达式对它进行排序 我的名单: 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 输出应按以下顺序进行: 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 简单地说,OrderByTimeOfDay: va

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

我的名单:

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
输出应按以下顺序进行:

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

简单地说,
OrderBy
TimeOfDay:

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

以上仅在所有日期相同时有效,如果日期也不同,您应执行以下操作

var sortedDates = dates.OrderByDescending(x => x);
或者不想使用,或者不认识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;
}
使用此解决方案

list<DateTime> YourList=new  list<DateTime> ();
.
.
.
YourList.OrderByDescending(x=>x.Date).ThenByDescending(x=>x.TimeOfDay).ToList()   
list YourList=新列表();
.
.
.
OrderByDescending(x=>x.Date)。然后ByDescending(x=>x.TimeOfDay)。ToList()

list.Sort((a,b)=>a.CompareTo(b))列表是您的列表变量。

对于以后的帖子,请尽量避免标题中的标签和所有类型的“感谢注释”。请随意讨论这个问题中使用的日期是否与本页上的日期相同:当我使用您的方法时,我收到以下错误:“无法将类型“System.Linq.IOrderedEnumerable”隐式转换为“System.Collections.Generic.List”。存在显式转换(是否缺少转换?)代码:Time是List:Times=Times.OrderBy(x=>x.TimeOfDay)@user2138160在末尾添加一个
ToList
调用。我将更新我的答案。请注意,OP发布的示例数据忽略了日期而忽略了时间。事实上,这个linq解决方案是唯一对我有效的解决方案。另一个没有很好地排序Datetime我添加了。last()用于获取最旧的更新,当另一个没有排序时,它工作得很好。
list<DateTime> YourList=new  list<DateTime> ();
.
.
.
YourList.OrderByDescending(x=>x.Date).ThenByDescending(x=>x.TimeOfDay).ToList()