Order List by Date and Time (in string format)

你说的曾经没有我的故事 提交于 2019-12-22 04:58:23

问题


Probably what I'm asking is quite simple but I don't seem to be getting this one out. I have a list of elements containing a Date field and a Time field. The Date field is a regular DateTime and the Time field is a string. Time is formatted like HH:mm and ranges in 24h.

Ordering my list by Date is simple by doing List.OrderBy(e => e.Date), but I don't seem to be able to later order it by Time so that the order of the records is according the date and the time.

I tried this out but it's probably a big mistake!

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

I hope someone can help me out with this one.


回答1:


You want OrderBy(...).ThenBy(...); and also - not that if the time is in HH:mm you don't have to parse it - you can just sort it alphabetically, i.e.

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

or via LINQ:

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



回答2:


why not try something like following:

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



回答3:


You know ThenBy() ?

List = List.OrderBy(DATE).ThenBy(Time)


来源:https://stackoverflow.com/questions/4943887/order-list-by-date-and-time-in-string-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!