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);
DateTime latestDate = myCollection. Where(r => r. ExpirationDate. HasValue) .
MaxBy() is now . MaxBy(). First() . This has the advantage that you can handle more than 1 result (used to be only the first person with the max age, but there may be more persons with the same age).
While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.
You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.
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.
You are almost there. Use Max:
DateTime? biggest = myCollection.Max(r=>r.ExpirationDate);
If all expiration dates are null or the collection is empty you will get Null as a result, otherwise the greatest date.
As you have commented on J. Sheens' answer that you want an DateTime as a result you will need to do something about any empty collection or no items with a value, you could do this with
DateTime biggest=myCollection.Max(r=>r.ExpirationDate) ?? DateTime.MinValue
This will give you DateTime.MinValue
instead of nulls in my previous example (it also has the advantage over using the any
clause that it iterates the collection once). I picked MinValue
as an example. You could use your own abitary date.
Using the DateTime? is better, because it allows you to use null for what it's meant to mean - undefined as MinValue
could be a valid item in your list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With