.Count()
是在 LINQ 中的一个扩展方法,基本上它使用了 .Count
。那么我想知道,在什么时候应该使用 Count()
,而在什么时候应该使用 .Count
?.Count()
是否更适用于尚未执行枚举的可查询集合?是否始终使用 .Count()
扩展方法会更加安全,或者反过来使用属性?还是这完全取决于集合本身?非常感谢任何建议或文章。
更新 1
在反编译 LINQ 的
.Count()
扩展方法后,发现如果 IEnumerable<T>
是一个 ICollection<T>
或 ICollection
,则它似乎使用了 .Count
属性,这也是大多数答案所建议的。现在我唯一真正看到的开销是额外的 null 和类型检查,这可能不是很大,但如果性能至关重要,它仍然可能产生一些影响。下面是 .NET 4.0 中反编译的 LINQ
.Count()
扩展方法。public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null)
{
return collection.Count;
}
ICollection collection2 = source as ICollection;
if (collection2 != null)
{
return collection2.Count;
}
int num = 0;
checked
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
}