I have a query that looks like this:
var qContactsOpen = from x in promo.Contacts
where x.type == type && (x.closure_id == 0 || x.closure_id == null)
orderby x.id descending
select new ContactsGrid
{
Id = x.id,
DescriptionA = x.description_A,
Address = x.address,
PostalCode = x.postal_code,
Vat = x.vat_iva,
CategoryDescription = x.Categories.description,
SpecializationDescription = x.Specializations.description,
AreaDescription = x.Areas.description,
Location = x.location,
Subject = x.subject,
Note = x.ContactsActivities.OrderByDescending(o=>o.date).FirstOrDefault().note
};
The last field in the select, is a string property, and I need that if x.ContactsActivities
is greater than 0, take the result or else take string empty.
If I run this, returns an error that it cannot orderby null.
It sounds you might just want:
Note = x.ContactsActivities
.OrderByDescending(o => o.date)
.Select(o => o.note)
.FirstOrDefault() ?? "";
By putting the projection earlier, it means you end up with the null result from FirstOrDefault
as the final result, rather than then trying to dereference the result to get at a note from a null reference.
The null-coalescing operator will then turn a null
value into the empty string. Note that means you'll get an empty string even if there was a result, if its note
property happened to have a null value.
See more on this question at Stackoverflow