c# – Count()(linq扩展名)和List.Count之间是否有区别

c# – Count()(linq扩展名)和List.Count之间是否有区别,第1张

概述List<string> list = new List<string>() {"a", "b", "c"};IEnumerable<string> enumerable = list;int c1 = list.Count;int c2 = list.Count();int c3 = enumerable.Count(); 最后3个陈述之间在性能和实施方面是否存在差异?将list.Co
List<string> List = new List<string>() {"a","b","c"};IEnumerable<string> enumerable = List;int c1 = List.Count;int c2 = List.Count();int c3 = enumerable.Count();

最后3个陈述之间在性能和实施方面是否存在差异?将List.Count()执行得更糟或与List.Count相同,并且如果引用的类型为IEnumerable< string> ?

解决方法 让我们看看Reflector:
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;    }    ICollection is3 = source as ICollection;    if (is3 != null)    {        return is3.Count;    }    int num = 0;    using (IEnumerator<TSource> enumerator = source.GetEnumerator())    {        while (enumerator.MoveNext())        {            num++;        }    }    return num;}

因此,如果您的IEnumerable<T>实现了ICollection<T>ICollection,它将返回Count属性.

总结

以上是内存溢出为你收集整理的c# – Count()(linq扩展名)和List.Count之间是否有区别全部内容,希望文章能够帮你解决c# – Count()(linq扩展名)和List.Count之间是否有区别所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1247420.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存