Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between Count() (linq extension) and List<T>.Count

Tags:

c#

list

List<string> list = new List<string>() {"a", "b", "c"};
IEnumerable<string> enumerable = list;

int c1 = list.Count;
int c2 = list.Count();
int c3 = enumerable.Count();

Are there differences in performance and implementation between these last 3 statements? Will list.Count() perform worse or the same as list.Count, and does it matter if the reference is of type IEnumerable<string> ?

like image 284
Bubblewrap Avatar asked Jun 23 '11 07:06

Bubblewrap


2 Answers

Let's look with Reflector:

public static int Count<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    ICollection<TSource> is2 = source as ICollection<TSource>;
    if (is2 != null)
    {
        return is2.Count;
    }
    ICollection is3 = source as ICollection;
    if (is3 != null)
    {
        return is3.Count;
    }
    int num = 0;
    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            num++;
        }
    }
    return num;
}

So, if your IEnumerable<T> implements ICollection<T> or ICollection, it will return the Count property.

like image 78
Paolo Moretti Avatar answered Sep 22 '22 21:09

Paolo Moretti


The Linq Count method is clever enough not to iterate over the underlying collection if it implements ICollection interface and therefore already has Count property.

like image 33
Giorgi Avatar answered Sep 20 '22 21:09

Giorgi