简体   繁体   中英

LINQ check if FirstOrDefault is null and use it

I'm writing a query that uses FirstOrDefault after an OrderBy query, which should check if it isn't null first then use some data in it. Is there a better way than writing it like this:

int count = db.Items.Count(i => 
          i.Assignments.OrderByDescending(a => 
                a.DateAssigned).FirstOrDefault() != null
          && 
          i.Assignments.OrderByDescending(a =>
                a.DateAssigned).FirstOrDefault().DateReturned == null)

What this code does is there are items that has many assignments, I take the latest assignment by date, then check if it exist, then run a condition on a property ( DateReturned ). As you see, this query is long, and most of my queries seem to look like this where I check for null first then run a second query on it using their properties. Is there a better way of doing this?

Just call .Any(a => a.DateReturned == null) to check whether there are any items that meet the condition.

If you only want to check the latest assignment, add .Take(1) before the .Any() .

My take:

int count = 
itemsQuery.Select(i => i.Assignments.OrderByDescending(a => a.DateAssigned))
          .Count(i => i.FirstOrDefault() != null &&  
                      i.First().DateReturned == null);

You can put the result in a variable to avoid doing the same thing twice:

int count = itemsQuery.Count(i => {
  var f = i.Assignments.OrderByDescending(a => a.DateAssigned).FirstOrDefault();
  return f != null && f.DateReturned == null;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM