LINQ 计算空值

LINQ Count null values

我正在做一个计算当前员工的简单饼图,我对 LINQ 还是个新手,所以我只想问有没有一种方法可以计算空值的总数?

到目前为止,这是我的代码:

public ActionResult PieCount()
{    
    int undefined = db.EMPs.Where(x => x.JS_REF == 1).Count();
    int regular = db.EMPs.Where(x => x.JS_REF ==2 ).Count();
    int contractual = db.EMPs.Where(x => x.JS_REF == 3).Count();
    int probationary = db.EMPs.Where(x => x.JS_REF ==4 ).Count();
    int notdefined = db.EMPs.Where(x => x.JS_REF == null ).Count();

    Ratio obj = new Ratio();

    obj.Undefined = undefined;
    obj.Contractual = contractual;
    obj.Regular = regular;
    obj.Probationary = probationary;
    obj.Notdefined = notdefined;

    return Json(new { result = obj }, JsonRequestBehavior.AllowGet);
}

目前为止一切正常,但是当我尝试计算空值时 "x.JS_REF == null" 我遇到了一个错误

这是错误: enter image description here

我的数据库: enter image description here

只需向您的 Count() 表达式添加一个谓词

int notdefined = db.EMPs.Count(x => x.JS_REF == 0);

int notdefined = db.EMPs.Count(x => String.IsNullOrEmpty(x.JS_REF.ToString()) == null);

注意:int不能为空。如果未为其设置值,那么我认为默认值为零。所以你应该检查你的 JS_REF 类型是 int 还是 int?


重构代码

您应该一次获取所有数据然后从中计数,而不是调用多次。

var data = db.EMPs.Where(x => 0 <= x.JS_REF && x.JS_REF <= 4).Select(p => p.JS_REF ).ToList();

int undefined = data.Count(x => x == 1);
int regular = ddata.Count(x => x == 2);
int contractual = data.Count(x => x == 3);
int probationary = data.Count(x => x == 4);
int notdefined = data.Count(x => x == 0);