I am trying to figure out how does ANY and ALL work in Linq.
Lets say I have 100k records in a list. Which one should perform faster?
if(recordsList.All(r => r.Deleted) == true) { }
or
if(recordsList.Any(r => r.Deleted == false) == false) { }
I would think that ANY should perform faster in case the first record on the list is deleted it should stop and return true, instead of using ALL which will always check whole list... right?
CodePudding user response:
See how Any
works internally:
public static bool Any<TSource>(this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
foreach (TSource local in source)
{
if (predicate(local))
{
return true;
}
}
return false;
}
So it stops once found a predicate that is evaluated to true.
In the same manner All
stops once a predicate that is evaluated to false:
public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
foreach (TSource current in source)
{
if (!predicate(current))
{
return false;
}
}
return true;
}
So I think the answer here is that both options should have similar to no difference.