Selecting earliest date using linq / lambda
I have the following expression
var list = techlinks.GetItems().Where(p => p.Status == 1).ToList();
I want to change this so that I would like to select the earliest date value like
var list = techlinks.GetItems().Where(p =>p.Date is earliest && p.Status == 1).ToList();
Please let me know which insert for p.Date is the earliest
thank
source to share
you can use OrderBy
or OrderByDescending()
to sort by date like this:
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
source to share
It depends a little on what makes GetItems()
of techLinks
, but something like this should work:
var list = techlinks.GetItems().Where(p => p.Date == techlinks.GetItems().Min(x => x.Date) && p.Status == 1).ToList();
If the method GetItems()
actually ends up in the database, you can first save its result and use it twice:
var allItems = techLinks.GetItems();
var list = allItems.Where(p => p.Date == allItems.Min(x => x.Date) && p.Status == 1).ToList();
source to share
If you only want 1, you can go with
techlinks.GetItems().Where(p => p.Status == 1).OrderBy(c => c.Date).FirstOrDefault();
otherwise I would split it into two statements
var date = techlinks.Min(c=>c.Date);
techlinks.GetItems().Where(p => p.Status == 1 && c.Date == date).ToList();
also know how your dates are inserted, DateTime.Now will add time components, so maybe this should do something gnarly like this
techlinks.GetItems().Where(p => p.Status == 1 && c.Date.Year == date.Year && c.Date.Month == date.Month && c.Date.Day == date.Day).ToList();
source to share