Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the earliest date in a LINQ expression

Tags:

c#

asp.net

linq

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?

like image 749
brother Avatar asked Mar 31 '16 06:03

brother


2 Answers

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()
like image 187
just.another.programmer Avatar answered Sep 28 '22 05:09

just.another.programmer


This way is more concise:

var earlyDate = i.Products.Min(p=>p.Date);

But you are sure that Product != null

like image 40
Nikolay Fedorov Avatar answered Sep 28 '22 03:09

Nikolay Fedorov