2011-02-09 115 views
5

可能我所问的很简单,但我似乎没有得到这一个。 我有一个包含日期字段和时间字段的元素列表。 Date字段是常规的DateTime,Time字段是字符串。 时间格式为HH:mm,范围在24h。按日期和时间排序的订单(字符串格式)

通过做List.OrderBy(e => e.Date)来按日期排列我的列表非常简单,但我似乎无法以后按顺序排序,因此记录的顺序依赖于日期和时间。

我试了一下,但它可能是一个很大的错误!

List = List.OrderBy(e => e.EstimatedDate).OrderBy(e => new TimeSpan(int.Parse(e.EstimatedTime.Substring(0,e.EstimatedTime.LastIndexOf(":"))),int.Parse(e.EstimatedTime.Substring(e.EstimatedTime.LastIndexOf(":")+1)),0).TotalMinutes); 

我希望有人能帮助我解决这个问题。

回答

10

你想OrderBy(...).ThenBy(...);也 - 不,如果时间是在HH:mm你没有对它进行解析 - 你可以排序它字母顺序排列,即

List = List.OrderBy(e => e.EstimatedDate).ThenBy(e => e.EstimatedTime).ToList(); 

或通过LINQ:

List = (from e in List 
     orderby e.EstimatedDate, e.EstimatedTime 
     select e).ToList(); 
+1

我知道这应该相当简单,今天我真的很困。你是第一个回答,我发现你的答案很好,所以你可以得到答案。感谢所有帮助过我的人。 – Hallaghan 2011-02-09 11:03:40

4

为什么不尝试类似如下:

List.OrderBy(e => e.Date).ThenBy(e => DateTime.Parse(e.Time)); 
// May need to change DateTime.Parse(e.Time) with appropriate conversion code 
2

你知道ThenBy()?

List = List.OrderBy(DATE).ThenBy(Time) 
相关问题