Accepted answer

For elegance, i would go by sorting the set based on the datetime field and returning the first item like:

set.OrderByDescending(x => x.DateTime)

This will create an in-memory representation of the sorted collection so efficiency is not that good. The most efficient solution for an unsorted set would be to loop over all items and save the newest. You can use linq for this by performing an aggregate operation which i find syntactically a mess.

Alternatively, you can store your items in a sorted collection like the SortedSet. This has a bit more complex insertion time 0(log2) instead of O(1) for most collections but it allows you to immidiatly sort on datetime and therefore selecting the newest item in O(1) rather than O(n).


Try Aggregate, i.e. something like:

list.Aggregate (
    (lastOne, current) => current.GreaterThan (lastOne) ? current : lastOne

i.e. if your field is DateTimeField, you should write something like

list.Aggregate (
    (lastOne, current) => 
        (lastOne == null) ||
             current.DateTimeField.GreaterThan (lastOne.DateTimeField)
        ? current
        : lastOne


Try that:

var newItem = myList.OrderByDescending(item => item.yourDateTimeField).First();


try this one

 sortlist.OrderByDescending(a => a.timeStamp).First();


Most of the solutions so far have to completely sort the list first (via OrderByDescending), which is unnecessary and time consuming. What you want is Jon Skeet's MoreLinq MaxBy function. Source for MaxBy is on google code.

var newest = thelist.MaxBy(x => x.DateTimeField);

Related Articles