Lore
Lore

Reputation: 45

Cannot implicitly convert type 'bool?' to 'bool' in a LinQ query?

My where statement fails obviously, but all I can find are samples on how to convert it outside of a LinQ query. The closest I can come is:

&& rdoNoPhone.Checked ? d.PHONE!= null : true

But, I am not quite sure how that works in my case. I understand the my SQL field called Active allows 3 values, trues, false and null and I am guessing that my answer is all in that little question mark.

LinQtoSQLDataContext db = new LinQtoSQLDataContext();
                   var query = from a in db.Admins
                               where a.Active = true
                               orderby a.Name
                               select new { a.Name, a.LoginName};

I should also ask how it is possible to use an SQL IN statement in a LinQ query. For example, changing the following into LinQ:

Select Field1, Field2, Level
From Table
Where Level IN (1,2,5)

Upvotes: 1

Views: 4870

Answers (1)

grovesNL
grovesNL

Reputation: 6075

I believe your equal sign in the line where a.Active = true should actually be two equal signs (to mean a comparison rather than an assignment). In fact, because you're comparing a bool to true, you don't even need a comparison operator. You can just write a.Active.Value.

LinQtoSQLDataContext db = new LinQtoSQLDataContext();
                   var query = from a in db.Admins
                               where a.Active.HasValue && a.Active.Value
                               orderby a.Name
                               select new { a.Name, a.LoginName};

For your second question, you can use Contains(value) to address this. For example:

int[] Levels = new int[] { 1, 2, 5 };
int Level = 2;
if (Levels.Contains(Level))
{
    // Level was found in Levels
}

Upvotes: 4

Related Questions