运算符'&&'不能应用于类型为'bool'和'bool?'的操作数
尝试读取这样的dataContext类
Trying to read a dataContext class like this
var users = new List<User>();
var roles = new int[] { 1, 2 };
// here I need to get users who's role is in role (1, 2), hence above line
// and also I need to get user who's isValid field true, please note that isValid is SQL 'bit' field and is nullable
//This is what I am doing
foreach (var user in dataContext.Users
.Where(u => roles.Contains(u.RoleID.Value)
&& u.isValid ?? false == true)) // here '&&' part I'm struggling and getting above error
{
users.Add(new User()
{
// Users Added in collection
});
}
所以问题出在where子句中,我需要获取角色为(1,2)&&的用户. isValid == true,如果isValid为'null',则将其设为false. 谢谢
So the question is in where clause I need to get user's who are in role(1,2) && isValid == true, if isValid is 'null' make it false. Thanks
您必须将其用括号括起来:
You have to wrap it in parentheses:
roles.Contains(u.RoleID.Value) && (u.isValid ?? false)
与(u.isValid?false)混淆,这并不意味着如果 u.isValid == null,然后将其设置为false,并在以下位置查找用户 u.isValid为假,这不是我想要的.
bit of confused with (u.isValid ?? false), does this not mean that if u.isValid == null then make it false and look for users where u.isValid is false, this is not what I want.
否,这仅表示将nulls
视为false
,并且所有用户都将isValid
既不是null
也不是false
.之所以起作用,是因为??
运算符将Nullable<bool>
转换为bool
,因此您可以将其与&&
一起使用.我不喜欢它,我更喜欢稍后会理解的显式代码:
No, it just means that nulls
are treated as false
and that all users are taken which isValid
is neither null
nor false
. It works because the ??
-operator converts the Nullable<bool>
to a bool
, so you can use it with &&
. I don't like it, i prefer explicit code that i understand later:
roles.Contains(u.RoleID.Value) && u.isValid.HasValue && u.isValid.Value
或更简单,通过将==
-运算符与bool?
一起使用:
or simpler by using the ==
-operator with the bool?
:
roles.Contains(u.RoleID.Value) && u.isValid == true