列表:数与数() [英] Lists: Count vs Count()

查看:96
本文介绍了列表:数与数()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个列表,这是首选方法来确定内部元素的数量

  VAR myList中=新的List<串> ;(); 

myList.Count
myList.Count()


解决方案

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



要证明哪一个我还有一点,这里是从反射器的代码 Enumerable.Count()

 公共静态诠释计数< TSource>(这个IEnumerable的< TSource>源)
{
如果(来源== NULL)
{
掷Error.ArgumentNull(源) ;
}
ICollection的< TSource> IS2 =源作为的ICollection< TSource取代;
如果(IS2!= NULL)
{
返回is2.Count;
}
INT NUM = 0;使用
(; TSource>的IEnumerator<枚举= source.GetEnumerator())
{
,而(enumerator.MoveNext())
{
NUM ++;
}
}
返回NUM;
}


Given a list, which method is preferred to determine the number of elements inside?

var myList = new List<string>();

myList.Count
myList.Count()

解决方案

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.

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;
}

这篇关于列表:数与数()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆