Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq All on empty collection

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.Definitions
                     .Where(x => propertyTypeIds.Contains(x.PropertyTypeId) && x.CountryId == countryId)
                     .GroupBy(x => x.PropertyTypeId)
                     .All(...some condition...);

How to rewrite this so All would return false on empty collection?

UPDATE: It is a LINQ to SQL and I wanted to execute this in single call.

UPDATE2: I think this works:

var exist = dbContext.Definitions
                     .Where(x => propertyTypeIds.Contains(x.PropertyTypeId) && x.CountryId == countryId)
                     .GroupBy(x => x.PropertyTypeId)
                     .Count(x => x
                        .All(...some condition...)) == propertyTypeIds.Count;
like image 746
jlp Avatar asked Aug 19 '16 12:08

jlp


1 Answers

If you're using LINQ to Objects, I'd just write my own extension method. My Edulinq project has sample code for All, and adapting that is pretty simple:

public static bool AnyAndAll<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> predicate)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }
    if (predicate == null)
    {
        throw new ArgumentNullException(nameof(predicate));
    }

    bool any = false;
    foreach (TSource item in source)
    {
        any = true;
        if (!predicate(item))
        {
            return false;
        }
    }
    return any;
}

This avoids evaluating the input more than once.

like image 77
Jon Skeet Avatar answered Sep 25 '22 13:09

Jon Skeet