Calculating Count for IEnumerable (Non Generic)

Homam picture Homam · Apr 9, 2011 · Viewed 37.6k times · Source

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?

Answer

Lasse Espeholt picture Lasse Espeholt · Apr 9, 2011
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;
    }
}