I have the following LINQ in a WebAPI controller:
MyDate = i.Products.FirstOrDefault().Date
It works as expected. But, Products is a Collection, so there can be many dates. The above just selects the first one.
What I really want to do is to find the date, with the earliest time, and select that one.
How would that look?
If you only want the date and not the whole product, it's a little clearer to use Max
or Min
.
MyDate = i.Products.Select(x => x.Date).Max()
If you actually want the product, you'll need to sort by the date and then select the first one.
MyProduct = i.Products.OrderBy(x => x.Date).FirstOrDefault()
This way is more concise:
var earlyDate = i.Products.Min(p=>p.Date);
But you are sure that Product != null
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