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? The simplest form would be: public static int Count(this IEnumerable source) { int c = 0; using (var e = source.GetEnumerator()) { while (e.MoveNext()) c++; } return c; } You can then improve on this by querying for ICollection : public static int Count(this IEnumerable source) { var col = source as ICollection; if (col != null) return col.Count; int c = 0; using (var e = source.GetEnumerator()) { while (e.MoveNext()) c++; } return c; }