简体   繁体   中英

Linq OrderBy in select if count is over 0

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.

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