Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ISNULL equivalent in Linq

I have a table with a column IsActive now I want to get a list of records with given status but I want to deal with IsActive with null values as false. In SQL we used:

SELECT * FROM dbo.Table c WHERE ISNULL(IsActive, 0) = @act 

How can in do this with LINQ?

P.S.: I'm using LINQ to Entities so I can't use a function to cast the value like:

Table.Where(t=> Parse(t.IsActive) == act)

bool Parse(bool? val){
    return val == true? true : false;
}

The way I could think of is:

Table.Where(t=> (t.IsActive==null || t.IsActive == false) && act == false)
              || (t.IsActive==true && act == true));

But this solution seems to be very poor and I think there should be a better way.

like image 306
Ashkan Mobayen Khiabani Avatar asked Feb 21 '16 12:02

Ashkan Mobayen Khiabani


1 Answers

You can use ?? operator instead of ISNULL:

Table.Where(t=> (t.IsActive ?? false) == act);
like image 137
Sergey Kalinichenko Avatar answered Oct 12 '22 02:10

Sergey Kalinichenko