Need OrderBy lambda expression with DateTime conversion

I am trying to create a lambda expression (Linq, C # 3.5) that can execute OrderBy on a value that has a String data type, but which actually contains a DateTime parsing.

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

The OrderBy clause below works correctly for ordering (as string data), but I really want to treat the values ​​as DateTimes and sort them by date. (SortColumn will 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 values ​​to a predicate for this? Any help appreciated!

+4
source share
2 answers

Rather rude and inefficient:

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

To reduce the number of searches / 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(); 
+7
source

Program the date / time value, and then sort it.

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

All Articles