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

+3


source to share


6 answers


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

      

+12


source


Here's another way.



var list=techlinks.GetItems()
                  .Where(p=>p.Status==1)
                    .Min(d => d.Date)
                      .Single();

      

+3


source


If there can be multiple items with the earliest date:

var list = techlinks.GetItems()
    .Where(p => p.Status == 1)
    .OrderBy(x=>x.Date)
    .GroupBy(x => x.Date)
    .First()
    .ToList()

      

+1


source


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

      

0


source


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

      

0


source


Student student = _context.Set<Student>()
          .Where(p => p.StudentID == ID.Value)
          .OrderBy(p => p.AddedDate)
          .FirstOrDefault();

      

0


source







All Articles