列表<T>任何或计数? [英] List<T> Any or Count?
本文介绍了列表<T>任何或计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我想对列表做某事时,我首先检查它是否不是 null
或不包含任何元素(不要吹 foreach
),我通常使用 list.Any()
但最好的选择是什么 - 使用 list.Count >0
,还是使用 list.Any()
?
When I want to do something with a list I first check it if is not null
or contains no elements (not to blow a foreach
) and I usually use list.Any()
but what is the best option - to use list.Count > 0
, or to use list.Any()
?
推荐答案
- 如果您使用的是
List
,请使用Count
,因为它知道它的大小. - 使用
Length
作为Array
- 如果你只有一个
IEnumerable
我会使用.Any()
而不是.Count()
因为它会更快,因为它会停止检查一项后. - Use
Count
if you're using aList
, since it knows its size. - Use
Length
for anArray
- If you just have an
IEnumerable
I would use.Any()
over.Count()
as it will be faster since it stops after checking one item.
另请查看此问题:哪种方法效果更好:.Any() vs .Count() >0?
这篇关于列表<T>任何或计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文