linq中要查询int?变量为null的情况时怎么办?

2025-04-28 01:14:23
推荐回答(4个)
回答1:

int countSchool(int? age) {
return sql.Student.Count(row => row.age == age ?? 这里写默认值);
}

例如

int countSchool(int? age) {
return sql.Student.Count(row => row.age == age ?? 20);
}

这就是当age传过来的值为空时,取默认值20

回答2:

处理null值,要用到Field泛型方法,具体操作不记得了,当时学linq是看到的,出自Apress的Pro Linq to SQL.
处理NULL,需要检查。
要不你试试这样呢:
return sql.Student.Count(row =>(int?) row.age == age);

回答3:

return sql.Student.Count(row => row.HasValue == false);
这样看看

回答4:

如果age为Null则替换成DBNull.Value
int countSchool(int? age) {
return sql.Student.Count(row => row.age == age??DBNull.Value);
}

我没尝试,你试试