Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Count for IEnumerable (Non Generic)

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?

like image 661
Homam Avatar asked Apr 09 '11 09:04

Homam


People also ask

How is IEnumerable count calculated?

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.

Does IEnumerable have count?

IEnumerable doesn't have a Count method.

What is the difference between count and count () in C#?

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.

How do I know if IEnumerable has an item?

enumerable. Any() is the cleanest way to check if there are any items in the list.


1 Answers

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;     } } 
like image 188
Lasse Espeholt Avatar answered Sep 20 '22 03:09

Lasse Espeholt