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 {}
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 {}