表数与数()?哪一个,为什么?

2023-09-04 00:37:10 作者:伤口撒盐丶痛的是心

我有对象的列表,也就是名单,其中,串> myList上{项目1,项目2,项目3,......} ,其方法是要求内计数的元素,为什么preferred? VAR数= myList.Count; 变种数myList.Count();

I have a list of object, i.e. List<string> myList { "Item1", "Item2", "Item3",... ... }, which method is preferred to call for counting the elements inside, and why? var count = myList.Count; or var count myList.Count(); ?

感谢。

推荐答案

计数()是LINQ推出一个扩展方法,而计数属性是列表本身的一部分(从的ICollection )。在内部,虽然,LINQ检查,如果你的的IEnumerable 工具的ICollection 键,如果这样做,使用计数属性。因此,在这一天结束的时候,有没有哪一个你用差列表

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.

要进一步证明我的观点,这里是由反射器的$ C $下 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;
}
相关推荐