Get the item which date is closest to now

c#, datetime, list

Solution

Using LINQ:

var item = list
    .Where(i => i.CARD_OF_DAY_DATE_CREATED > DateTime.Now)
    .OrderBy(i => i.CARD_OF_DAY_DATE_CREATED)
    .First();

Problem

In my database I have a list of items with the following property: ``` public System.DateTime CARD_OF_DAY_DATE_CREATED { get; set; } ``` I need to get the item which `CARD_OF_DAY_DATE_CREATED` is the closest to `DateTime.Now` using c#. I could do massive for/foreach loops, but I was wondering if there was a good, efficient way to do it with anything? Note: The `CARD_OF_DAY_DATE_CREATED` field needs only to be checked forward, meaning that checking if the `CARD_OF_DAY_DATE_CREATED` is yesterday would be non-relevant because those items won't be in the list.

Original source