c# - How do I get the latest date from a collection of objects using LINQ? -
i have list of objects , each object has expirationdate property of type datetime. want retrieve latest date in list. there elegant way of doing through linq?
something like:
datetime latestdate = mycollection.where(r=>r.expirationdate.hasvalue).maxdate(r=>r.expirationdate.value);
datetime? latestdate = mycollection.max(r => r.expirationdate);
intellisense should have given max() method. =)
now, if must assign datetime, consider doing thus:
datetime latestdate = mycollection.where(r => r.expirationdate.hasvalue) .max(r => r.expirationdate) .value;
this not cover case of empty collection or collection null expirationdates.
depending on earlier logic, checking
mycollection.any(r => r.expirationdate.hasvalue)
might idea before trying assign value.
Comments
Post a Comment