brother
brother

Reputation: 8151

Get the earliest date in a LINQ expression

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?

Upvotes: 16

Views: 11511

Answers (8)

Aakarshan Maharjan
Aakarshan Maharjan

Reputation: 21

Simple, if you need earliest use OrderBy and need oldest then use OrderByDescending.

 i.Products.OrderBy(x => x.Date).Select(x => x.Date).FirstOrDefault();
 i.Products.OrderByDescending(x => x.Date).Select(x => x.Date).FirstOrDefault();

Upvotes: 2

Nikolay Fedorov
Nikolay Fedorov

Reputation: 387

This way is more concise:

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

But you are sure that Product != null

Upvotes: 4

bit
bit

Reputation: 4487

Here is a lambda expression that will give you the minimum (earliest) date

DateTime earliestDate = i.Products.Min(p => p.Date);

Upvotes: 2

Baahubali
Baahubali

Reputation: 4802

i.Products.OrderBy(x => x.Date).FirstOrDefault().Date;

It has to be orderby and not orderbydescending. orderbydescending will give you the latest date first and order by will give you the earliest date first.

Upvotes: 1

just.another.programmer
just.another.programmer

Reputation: 8785

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()

Upvotes: 21

maulik sakhare
maulik sakhare

Reputation: 2037

Optimized way would be :

i.Products.OrderByDescending(x => x.Date).Select(x => x.Date).FirstOrDefault();

Upvotes: 1

Alok Gupta
Alok Gupta

Reputation: 1360

You can use

 i.Products.OrderByDescending(x => x.Date).FirstOrDefault().Date;

Upvotes: 2

Marc
Marc

Reputation: 3959

Simply order by date:

MyDate = i.Products.OrderBy(x => x.Date).Select(x => x.Date).FirstOrDefault();

Upvotes: 1

Related Questions