LINQ check if FirstOrDefault is null and use it

c# entity-framework linq

Question

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?

1
1
8/23/2012 5:09:48 PM

Accepted Answer

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

8
8/23/2012 5:07:51 PM

Popular Answer

My take:

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow