列表:Count 与 Count() [英] Lists: Count vs Count()
问题描述
给定一个列表,首选哪种方法来确定里面的元素数量?
Given a list, which method is preferred to determine the number of elements inside?
var myList = new List<string>();
myList.Count
myList.Count()
推荐答案
Count()
是 LINQ 引入的扩展方法,而 Count
属性是 List 的一部分本身(派生自 ICollection
).但在内部,LINQ 会检查您的 IEnumerable
是否实现了 ICollection
,如果实现了,则使用 Count
属性.因此,归根结底,您将哪个用于 List
并没有区别.
Count()
is an extension method introduced by LINQ while the Count
property is part of the List itself (derived from ICollection
). Internally though, LINQ checks if your IEnumerable
implements ICollection
and if it does it uses the Count
property. So at the end of the day, there's no difference which one you use for a List
.
为了进一步证明我的观点,这里是来自 Reflector 的 Enumerable.Count()
To prove my point further, here's the code from Reflector for Enumerable.Count()
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;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
这篇关于列表:Count 与 Count()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!