C# – How to get the latest date from a collection of objects using LINQ

c++collectionslinq

I have a list of objects and each object has a ExpirationDate property which is of type DateTime. I want to retrieve the latest date in the list. Is there an elegant way of doing that through LINQ?

Something like:

DateTime latestDate =  myCollection.Where(r=>r.ExpirationDate.HasValue).MaxDate(r=>r.ExpirationDate.Value);

Best Solution

DateTime? latestDate = myCollection.Max(r => r.ExpirationDate);

Intellisense should have given you the Max() method. =)


Now, if you must assign it to a DateTime, I would consider doing thus:

DateTime latestDate = myCollection.Where(r => r.ExpirationDate.HasValue)
                                  .Max(r => r.ExpirationDate)
                                  .Value;

This will not cover the case of an empty collection or a collection with only null ExpirationDates.


Depending on your earlier logic, checking

myCollection.Any(r => r.ExpirationDate.HasValue)

might be a good idea before trying to assign a value.