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);
Intellisense should have given you the Max() method. =)
Now, if you must assign it to a DateTime, I would consider doing thus:
This will not cover the case of an empty collection or a collection with only null ExpirationDates.
Depending on your earlier logic, checking
might be a good idea before trying to assign a value.