What are the key differences between IEnumerable Count() and Length?
Little addition to Jon Skeet's comment.
Here is the source code of the Count() extension method:
.NET 3:
public static int Count(this IEnumerable source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection is2 = source as ICollection;
if (is2 != null)
{
return is2.Count;
}
int num = 0;
using (IEnumerator enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
.NET 4:
public static int Count(this IEnumerable source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection is2 = source as ICollection;
if (is2 != null)
{
return is2.Count;
}
ICollection is3 = source as ICollection;
if (is3 != null)
{
return is3.Count;
}
int num = 0;
using (IEnumerator enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}