Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting earliest date using linq/lambda

Tags:

c#

lambda

linq

I have following expression

 var list = techlinks.GetItems().Where(p =>  p.Status == 1).ToList();

I want to change this so that I want to select the earliest date value for example

 var list = techlinks.GetItems().Where(p =>p.Date is earliest && p.Status == 1).ToList();

Please let me know what to insert for p.Date is earliest

Thanks

like image 860
J. Davidson Avatar asked Oct 01 '14 17:10

J. Davidson


4 Answers

Here's another way.

var list=techlinks.GetItems()
                  .Where(p=> p.Status==1)
                    .Min(d => d.Date)
                      .Single();
like image 178
The One Avatar answered Sep 28 '22 07:09

The One


you can use OrderBy or OrderByDescending() to sort them on Date this way:

var list = techlinks.GetItems()
                    .Where(p => p.Status == 1)
                    .OrderBy(x=>x.Date).First(); // this will give oldest date

and:

var list = techlinks.GetItems()
                    .Where(p => p.Status == 1)
                    .OrderByDescending(x=>x.Date).First(); // this will give latest date
like image 26
Ehsan Sajjad Avatar answered Sep 28 '22 07:09

Ehsan Sajjad


Student student = _context.Set<Student>()
          .Where(p => p.StudentID == ID.Value)
          .OrderBy(p => p.AddedDate)
          .FirstOrDefault();
like image 21
Oracular Man Avatar answered Sep 28 '22 08:09

Oracular Man


If there might be multiple items all with the earliest date:

var list = techlinks.GetItems()
    .Where(p => p.Status == 1)
    .OrderBy(x=>x.Date)
    .GroupBy(x => x.Date)
    .First()
    .ToList()
like image 28
Dave Mackersie Avatar answered Sep 28 '22 08:09

Dave Mackersie