Linq All on empty collection

后端 未结 8 2124
面向向阳花
面向向阳花 2021-01-08 00:24

I need to check if all definitions contains some specific data. It works fine except the case when GroupBy returns empty collection.

var exist = dbContext.De         


        
8条回答
  •  既然无缘
    2021-01-08 01:02

    Edit: first answer wouldn't have worked.

    If you rearrange your query somewhat, you can use DefaultIfEmpty without needing to change your condition:

    var exist = dbContext.Definitions
                         .Where(x => propertyTypeIds.Contains(x.PropertyTypeId) 
                                      && x.CountryId == countryId)
                         .GroupBy(x => x.PropertyTypeId);
    
               // apply the condition to all entries, 
               // resulting in sequence of bools (or empty), 
               // to permit the next step
                         .Select(...some condition...) 
    
               //if seq is empty, add `false`
                         .DefaultIfEmpty(false)
    
               //All with identity function to apply the query and calculate result
                         .All(b => b)
             );
    

提交回复
热议问题