LINQ当集合为空的时候,如何使用Max,Min,Sum等聚合函数?

Q: LINQ当集合为空的时候,使用Max,Min,Sum等聚合函数会导致InvalidOperationException异常

A:

把类型转为可空类型

NorthwindDataContext northwind = new NorthwindDataContext();
 var chineseEmployees 
= from employee in northwind.Employees 
                         
where employee.Country == "China" 
                         select employee; 
//没有国家为中国的,所以查询出空集
DateTime? newestHireDate = chineseEmployees.Max(employee => (DateTime?)employee.HireDate);
if (newestHireDate.HasValue){}
else {}
posted @ 2009-05-13 15:02  东东呛  阅读(1759)  评论(0编辑  收藏  举报