给定一个列表,首选哪种方法来确定内部元素的数量?
var myList = new List<string>();
myList.Count
myList.Count()
Count()
是 LINQ 引入的扩展方法,而Count
属性是列表本身的一部分(源自ICollection
)。通过内部,LINQ 检查您的IEnumerable
实施ICollection
如果是的话,它会使用Count
财产。因此,归根结底,您使用哪一个进行测试并没有什么区别List
.
为了进一步证明我的观点,这是来自 Reflector 的代码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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)