Why is this linq extension method hit the database twice?

Posted by Pure.Krome on Stack Overflow See other posts from Stack Overflow or by Pure.Krome
Published on 2010-02-13T13:52:45Z Indexed on 2010/05/10 17:24 UTC
Read the original article Hit count: 249

Filed under:
|
|

Hi folks,

I have an extension method called ToListIfNotNullOrEmpty(), which is hitting the DB twice, instead of once. The first time it returns one result, the second time it returns all the correct results.

I'm pretty sure the first time it hits the database, is when the .Any() method is getting called.

here's the code.

public static IList<T> ToListIfNotNullOrEmpty<T>(this IEnumerable<T> value)
{
    if (value.IsNullOrEmpty())
    {
        return null;
    }
    if (value is IList<T>)
    {
        return (value as IList<T>);
    }
    return new List<T>(value);
}

public static bool IsNullOrEmpty<T>(this IEnumerable<T> value)
{
    if (value != null)
    {
        return !value.Any();
    }
    return true;
}

I'm hoping to refactor it so that, before the .Any() method is called, it actually enumerates through the entire list.

If i do the following, only one DB call is made, because the list is already enumerated.

var pewPew = (from x in whatever
              select x)
             .ToList()   // This enumerates.
             .ToListIsNotNullOrEmpty();  // This checks the enumerated result.

I sorta don't really want to call ToList() then my extension method. Any ideas, folks?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about LINQ