I would use Enumerable.Any
instead of Enumerable.Count
:
results.Where(r => r.Categories.Intersect(submittedCategories).Any())
Method Count()
has optimization for sources which implement ICollection
(it simply returns Count
property value of collection). But result of Enumerable.Intersect
will be IEnumerable<T>
so in this case Count()
will iterate over all set:
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
throw Error.ArgumentNull("source");
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
return is2.Count;
ICollection is3 = source as ICollection;
if (is3 != null)
return is3.Count;
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext()) // you will fall into this case
num++;
}
return num;
}
It means that full intersection should be built from both collections to know total count of items in result. And only then value will be compared with zero.
Any()
will stop iterating just after first item will be found without finding all items which intersect.
public static bool Any<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
throw Error.ArgumentNull("source");
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
return true;
}
return false;
}
Another benefit - Any()
shows your intent better.