Selecting earliest date using linq/lambda

2019-06-19 00:55发布

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

标签: c# linq lambda
6条回答
啃猪蹄的小仙女
2楼-- · 2019-06-19 01:28

Here's another way.

var list=techlinks.GetItems()
                  .Where(p=>p.Status==1)
                    .Min(d => d.Date)
                      .Single();
查看更多
地球回转人心会变
3楼-- · 2019-06-19 01:32

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();
查看更多
Explosion°爆炸
4楼-- · 2019-06-19 01:33

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()
查看更多
forever°为你锁心
5楼-- · 2019-06-19 01:34
Student student = _context.Set<Student>()
          .Where(p => p.StudentID == ID.Value)
          .OrderBy(p => p.AddedDate)
          .FirstOrDefault();
查看更多
6楼-- · 2019-06-19 01:45

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
查看更多
啃猪蹄的小仙女
7楼-- · 2019-06-19 01:47

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();
查看更多
登录 后发表回答