简体   繁体   中英

LINQ Count null values

I'm doing a simple Pie chart that counts current employee, I'm still new to LINQ so I just want to ask is there a way to total count null values?

Here's my code so far:

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);
}

It's working so far but when I tried to count null value "x.JS_REF == null" I'm getting an error

here's the error: enter image description here

My database: enter image description here

Just add a predicate to your Count() expression

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

or

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

Note that: int cannot be null. If a value is not set to it, then the default value I believe is zero. So you should check your type of JS_REF is int or int?


Refactor code

You should get all data at one time then count from them instead of calling multiple times.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM