c# - 我是否需要在 foreach 之前检查 Enumerable 的 Count()

标签 c#

在迭代/foreaching 集合之前检查 Enumerable 的 Count() 是否有任何速度改进或确实有必要?

List<int> numbers = new List<int>();

if(numbers.Count() > 0)
{
    foreach(var i in numbers) {/*Do something*/}
}

最佳答案

不,反之亦然。如果它不是一个集合(如 ListArray )而是一个延迟执行的查询,它必须完全执行,这可能非常昂贵,只是为了确定计数。在您的示例中,它实际上是 List , Enumerable.Count足够聪明,可以尝试将其转换为 ICollection<T>/ICollection第一的 。如果这成功了 Count属性(property)被使用。

所以只需使用 foreach .如果序列为空也没有坏处,循环将立即退出。

出于同样的原因,最好使用 Enumerable.Any而不是 Count() > 0如果您只想检查一个序列是否至少包含一个元素。意图也更加明确。

关于c# - 我是否需要在 foreach 之前检查 Enumerable 的 Count(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20990717/

相关文章:

c# - DbMigration 使用数据移动列

c# - 在 Linux 上使用 C# 和 Mono 构建控制台应用程序来解密 cookie,如何确保可以访问 .dll

c# - Repeater 在 PostBacks 上丢失了它的数据

c# - 如何初始化Point数组?

c# - "The path .. would result in a file outside the App Bundle and cannot be used"错误,单触摸/Xamarin

c# - Task.Run 与 null SynchronizationContext

c# - 将图像旋转 X 度 C# wpf

c# - 我可以获取其他ElasticSearch索引设置吗?

c# - 文件详细信息选项卡中的 "Language neutral"属性

c# - 使用 MySqlCommand 执行存储过程时出现 SqlNullValueException