Linq All on empty collection

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

    Here's the alternative to All that returns false if collection is empty:

    var collection = Enumerable.Range(0, 0); //empty collection
    
    collection
      .Select(IsValid)
      .DefaultIfEmpty(false)
      .All(b => b);
    

    Or as an extension method:

    public static bool AnyAndAll(IEnumerable collection, Func predicate) =>
      collection
        .Select(predicate)
        .DefaultIfEmpty(false)
        .All(b => b);
    

提交回复
热议问题