Operator '&&' cannot be applied operands to bool and bool?
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?
@mjwills I posted sample code, main concern is not able to null check somelist
– dchennaraidu
Jul 3 at 6:36
What is
somelist
?– haim770
Jul 3 at 6:39
somelist
This is where a Minimal, Complete, and Verifiable example would be great.
– Enigmativity
Jul 3 at 6:43
4 Answers
4
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.
somelist?.contains(t.id)
null
So you should try like this
&& (somelist!=null ? somelist.contains(t.id) : false)
Check : 3 misuses of ?. operator in C# 6
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>();
}
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();
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
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
The above code does not compile.
– mjwills
Jul 3 at 6:28