Chenna
Chenna

Reputation: 2623

Operator '&&' cannot be applied operands to bool and bool?

Sample query

var users = (from t in T_Table
            join x in X_Table on t.id equals x.id
            where t.pid == x.pid
            && somelist.contains(t.id) //UNABLE TO APPLY somelist?.contains
            select (new User(){name = t.user})).ToList();

I'm unable null check somelist.

It shows:

Operator '&&' cannot be applied operands to bool and bool?

Upvotes: 1

Views: 7330

Answers (4)

Dom84
Dom84

Reputation: 864

check if somelist is not null first before accessing contains.

var users = (from t in T_Table
            join x in X_Table on t.id equals x.id
            where t.pid == x.pid
            && somelist != null && somelist.contains(t.id) //UNABLE TO APPLY somelist?.contains
            select (new User(){name = t.user})).ToList();

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176896

problem here is if you write like this

somelist?.contains(t.id) return null in case somelist is null and null is not boolean value.

So you should try like this

  &&  (somelist!=null ? somelist.contains(t.id) : false)

Check : 3 misuses of ?. operator in C# 6

Upvotes: 4

Sowdhanya
Sowdhanya

Reputation: 63

First check whether somelist is having any data or not, if somelist is null you can't operate contains on somelist

or

Where(u => somelist.Contains(t.Id.Value)) 

should also work if somelist is not null

Upvotes: -1

fubo
fubo

Reputation: 45947

Your error occurs becasue

bool b1 = true;
bool? b2 = true;
bool result = b1 && b2; //b2 could also be null

There are two ways to solve this.

1

bool result = b1 && b2 == true;  // somelist?.contains() == true

2

make sure your item can't be null before you run your query (this also works for linq2SQL) so you don't need a null-conditional operator in your query

if(somelist == null)
{
   somelist = new List<yourType>();
}

Upvotes: 4

Related Questions