Need lambda expression OrderBy with DateTime conversion

与世无争的帅哥 提交于 2019-12-10 17:25:50

问题


I am trying to create a lambda expression (Linq, C# 3.5) that can perform a OrderBy on a value that is of data type String but which actually contains a parse-able DateTime.

For example, typical values may be "5/12/2009" , "1/14/2008", etc.

The OrderBy clause below works correctly for ordering (as if string data), but I actually want to treat the values as DateTimes, and perform the sort by Date. (The sortColumn would be something like "dateCreated".)

List<MyObject> orderedList = unorderedList.OrderBy(p => p.Details.Find(s => s.Name == sortColumn).Value).ToList();

Is there a way to convert the values in the predicate to do this? Any help appreciated!


回答1:


Rather gross and inefficient:

List<MyObject> orderedList = unorderedList.OrderBy(p => DateTime.Parse(p.Details.Find(s => s.Name == sortColumn).Value)).ToList();

To reduce the number of lookups/parsing:

List<MyObject> orderedList =
    (from extracted in (from p in unorderedList
                        select new { Item = p, Date = DateTime.Parse(p.Details.Find(s => s.Name == sortColumn).Value })
     orderby extracted.Date
     select extracted.Item)
    .ToList();



回答2:


Project the date/time value and then sort by it.

var orderedList =
    (from p in unorderedList
     let value = DateTime.Parse(p.Details.Find(s => s.Name == sortColumn).Value)
     orderby value
     select p)
     .ToList();


来源:https://stackoverflow.com/questions/1213956/need-lambda-expression-orderby-with-datetime-conversion

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