Count()(linq扩展名)和List <T> .Count之间有区别吗?

Bub*_*rap 7 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();
Run Code Online (Sandbox Code Playgroud)

最后3个陈述之间在性能和实施方面是否存在差异?将list.Count()表现更差或相同list.Count,如果引用类型IEnumerable<string>是否重要?

Pao*_*tti 10

让我们看看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;
}
Run Code Online (Sandbox Code Playgroud)

所以,如果你的IEnumerable<T>工具ICollection<T>或者ICollection,它会返回Count属性.