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
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
Here's another way.
var list=techlinks.GetItems()
.Where(p=>p.Status==1)
.Min(d => d.Date)
.Single();
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()
It slightly depends on what GetItems()
of techLinks
does, but something like that should work:
var list = techlinks.GetItems().Where(p => p.Date == techlinks.GetItems().Min(x => x.Date) && p.Status == 1).ToList();
If GetItems()
method actually hits the database, you can store its result first and use it twice:
var allItems = techLinks.GetItems();
var list = allItems.Where(p => p.Date == allItems.Min(x => x.Date) && p.Status == 1).ToList();
If you only want 1 you could go with
techlinks.GetItems().Where(p => p.Status == 1).OrderBy(c => c.Date).FirstOrDefault();
otherwise I'd break it up into two statements
var date = techlinks.Min(c=>c.Date);
techlinks.GetItems().Where(p => p.Status == 1 && c.Date == date).ToList();
also be aware of how your dates are inserted, DateTime.Now will add time components so might have to 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();
Student student = _context.Set<Student>()
.Where(p => p.StudentID == ID.Value)
.OrderBy(p => p.AddedDate)
.FirstOrDefault();