In a collection we can easily check if there is any (particular) item:
This is a very efficient way to check because it doesn't enumerate the whole collection. After enumerating the first element, the Any() method returns the result. This saves time if the collection is large or enumeration goes slow.
We still have to enumerate the whole collection if we need to know if a collection has one element, multiple elements or we need to compare the count. This is not efficient.
I created methods that counts the elements but not the whole collection. You can use it like this:
This is the implementation of the methods
Hi Alex,
This indeed is handy to have around. I think you can reduce some redundant code by using 'pain old' Where() to filter in the overload with the predicate
private static int CountCompareTo<T>(this IEnumerable<T> source, int value, Func<T, bool> predicate)
{
return source.where(predicate).CountCompareTo(source, value);
}
Regards Frank
Hi Frank,
Thanks for your suggestion. This saves a lot of code. Less code means less errors, less maintenance...
I will update the production code ald leave this this post as posted.
Regards,
Alex