原文(http://www.cnblogs.com/ldp615/archive/2011/12/11/2284154.html)

Linq 出现之前,我们通常使用下面的方式来判断集合是否非空,即集合包含元素:

 var array = new int[];
var b1 = array.Length > ; var list = new List<string>();
var b2 = list.Count > ; var collection = new Collection<double>();
var b3 = collection.Count > ;

使用 Length 或 Count 属性,上面的写法没有问题。

但到了 Linq 时代,Enumerable.Count 扩展方法“统一了“ Length 和 Count 属性,于是就有了下面判断非空的写法:

 public static void SomeAction<T>(IEnumerable<T> source){
if (source.Count() > ){
//...
}//...
}

这种写法可以,运行也正常,但可能会产生非常严重的性能的问题

注意是可能,并不是一定,上面的方法如果传入的是 Array、List<T>或Collection<T>,不会有问题。

那么什么时候会出问题呢?我们来看如下方法:

public static IEnumerable<int> GetNums(int start, int count)
{
var end = start + count;
for (int i = start; i < end; i++)
yield return i;
}

  如下调用时:

var nums = GetNums(, int.MaxValue);
SomeAction(nums);

执行速度会相当慢,我的电脑大约用了 70 秒的时间来执行 source.Count() > 0。

分析下的话,你会发现 GetNums 第 5 行代码 yield return i 执行了 int.MaxValue 次,有必要吗?

其实只要返回一个元素我们就可以断定集合非空,完全不需要将所有的元素返回。

那又如何来判断呢?我们可以使用 Enumerable.Any 扩展方法:

将 SomeAction 方法修改如下:

public static void SomeAction<T>(IEnumerable<T> source){
if(source.Any()){ // 切勿使用 source.Count() > 0
//...
}//...
}

再次调用 ,你会发现执行时间可以忽略不计了。

总结下规律, Count() > 0 遇上 yeild return 必定会出现性能问题

Enumerable.Any 扩展方法可以解决我们的问题,但这个方法在命名上似乎有些问题,总感觉有点不顺,如若判断集合为空:

if (!source.Any()) { //...
}

! source.Any() 更显得绕口,我们可以新增两个扩展方法 IsEmpty、IsNotEmpty 来解决,请参考:

c# 扩展方法奇思妙用基础篇十:IsEmpty、IsNotEmpty 扩展

Linq:切勿使用 Count() > 0 来判断集合非空的更多相关文章

  1. 用Count() > 0 来判断集合非空的问题

    Linq 出现之前,我们通常使用下面的方式来判断集合是否非空,即集合包含元素: ]; ; var list = new List<string>(); ; var collection = ...

  2. mysql 5.7中 count(0) count(*) count(主键) count(非空字段)效率比较

    mysql count(0) count(*) count(主键) count(非空字段) 效率比较 写代码的时候经理在背后说了一句count(0)的效率高于count(*) ,索性全部测试了一下 结 ...

  3. LINQ体验(2)——C# 3.0新语言特性和改进(上篇)

    整体来说.Visual Studio 2008和.NET 3.5是建立在.NET2.0核心的基础之上,.NET2.0核心本身将不再变化(假设不了解.NET2.0的朋友,请參看MSDN或者一些经典的书籍 ...

  4. org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

    org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actua ...

  5. Oracle > count(*) / count(0) / count(1) | order by 1, 2

    select count(*), select count(0), select count(1) from table 在统计表的行数时候,经常用到 select count(*) 然而对于行数很多 ...

  6. 20.org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

    org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actua ...

  7. 关于Hibernate级联更新插入信息时提示主键不为空的问题“org.hibernate.StaleStateException: Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1 ”

    org.hibernate.StaleStateException: Batch update returned unexpected row count from update: 0 actual ...

  8. 关于Error during managed flush [Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1]错误

    控制台报错: 08:07:09.293 [http-bio-8080-exec-2] ERROR org.hibernate.internal.SessionImpl - HHH000346: Err ...

  9. Select count(*)、Count(1)、Count(0)的区别和执行效率比较

    记得很早以前就有人跟我说过,在使用count的时候要用count(1)而不要用count(*),因为使用count(*)的时候会对所有的列进行扫描,相比而言count(1)不用扫描所有列,所以coun ...

随机推荐

  1. C#调用VB6写的ActiveX Dll

    搜索了很多资料,下载了Demo:http://download.csdn.net/detail/xieguoxian/2747484然后在同学电脑上测试才弄好...记录下 (一) 前期搜索资料: VB ...

  2. let关键字

    作用: 与var类似, 用于声明一个变量特点: 只在块作用域内有效 不能重复声明 不会预处理, 不存在提升应用: 循环遍历加监听 //应用实例 <body> <button>测 ...

  3. jquery,js常用特效名称

  4. JavaScript split()

    http://www.w3school.com.cn/jsref/jsref_split.asp

  5. Masters of Doom

    http://blog.codinghorror.com/you-dont-need-millions-of-dollars/ "In the information age, the ba ...

  6. C# 获取远程xml文件

    /// <summary> /// 加载远程XML文档 /// </summary> /// <param name="URL"></pa ...

  7. C#传值

    C#若不加限制传值时自带的类型为值传递,自创的类型为引用传递 using System; using System.Collections.Generic; using System.Linq; us ...

  8. python中raw_input()与input()

    raw_input([prompt]) input([prompt]) # prompt:如果参数存在,直接输出到屏幕上,不会再另起一行 raw_input 如其字面意思一样,返回输入字符的字符串形式 ...

  9. 内存管理pbuf.c源码解析——LwIP学习

    声明:个人所写所有博客均为自己在学习中的记录与感想,或为在学习中总结他人学习成果,但因本人才疏学浅,如果大家在阅读过程中发现错误,欢迎大家指正. 本文自己尚有认为写的不完整的地方,源代码没有完全理清, ...

  10. IT编程培训,线上线下,孰优孰劣

    现在Java培训机构确实参差不齐,主要有在线培训和线下培训两大类: 1,虚拟和现实的区别:不论视觉,听觉,体验上在线教学都不如线下教学. 2,学费问 题:在线教学由于成本低,不受地域,教学设备限制一般 ...