Linq All on empty collection

后端 未结 8 2068
面向向阳花
面向向阳花 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 00:56

    Here is another trick:

    var exist = dbContext.Definitions
        .Where(x => propertyTypeIds.Contains(x.PropertyTypeId) && x.CountryId == countryId)
        .GroupBy(x => x.PropertyTypeId)
        .Min(some_condition ? (int?)1 : 0) == 1;
    

    It utilizes the fact that the above Min method returns:

    (A) null when the set is empty
    (B) 0 if the condition is not satisfied for some element
    (C) 1 if the condition is satisfied for all elements

    so we simple check the result for (C) using the nullable value comparison rules.

提交回复
热议问题