Linq All on empty collection

后端 未结 8 2053
面向向阳花
面向向阳花 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:17

    You could make use of DefaultIfEmpty extension method, and adjust your some condition so that it evaluates null to false.

    var exist = definitions
        .Where(x => propertyTypeIds.Contains(x.PropertyTypeId) && x.CountryId == countryId)
        .GroupBy(x => x.PropertyTypeId)
        .DefaultIfEmpty()
        .All(...some condition...));
    
    0 讨论(0)
  • 2021-01-08 01:17

    Well, you can do it in two steps :

    var definitions = definitions.Where(
                        x => propertyTypeIds.Contains(x.PropertyTypeId) && x.CountryId == countryId)
                         .GroupBy(x => x.PropertyTypeId);
    
    var exist = definitions.Any() && definitions.All(...some condition...);
    
    0 讨论(0)
提交回复
热议问题