Can anyone help me with a Count
extension method for IEnumerable
(non generic interface).
I know it is not supported in LINQ but how to write it manually?
IEnumerable has not Count function or property. To get this, you can store count variable (with foreach, for example) or solve using Linq to get count.
IEnumerable doesn't have a Count method.
So why do we care about the difference between Count and Count()? One simply reads a value in memory to determine the count of the elements in a collection and the other iterates over the entire collection in memory to determine the count of the number of items.
enumerable. Any() is the cleanest way to check if there are any items in the list.
yourEnumerable.Cast<object>().Count()
To the comment about performance:
I think this is a good example of premature optimization but here you go:
static class EnumerableExtensions { public static int Count(this IEnumerable source) { int res = 0; foreach (var item in source) res++; return res; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With