Sort list of dates closest to current date

c#, datetime, sorting

Solution

You can order them by the absolute difference between the node's time and the current time. You can get the absolute time of a `TimeSpan` with the Duration method:

DateTime now = DateTime.Now;
var ordered = nodes.OrderBy(n => (now - DateTime.Parse(n.GetProperty("date").Value)).Duration())

Problem

I have to a list of objects which has a DateTime property and I need to sort this list so that the objects with the closest date to `DateTime.Now` is first in the list. I have tried the following: ``` nodes.Sort((x, y) => DateTime.Compare( DateTime.Now, DateTime.Parse(x.GetProperty("date").Value))); ``` But this doesn't return a correct result. Does anyone know of a good way to do this? :-)

Original source