运算符'&&'不能应用于类型为'bool'和'bool?'的操作数 [英] Operator '&&' cannot be applied to operands of type 'bool' and 'bool?'

查看:218
本文介绍了运算符'&&'不能应用于类型为'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

这篇关于运算符'&amp;&'不能应用于类型为'bool'和'bool?'的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆