Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator '&&' cannot be applied to operands of type 'bool' and 'bool?' [duplicate]

Tags:

c#

linq

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
    });
}

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

like image 681
sky Avatar asked Oct 17 '14 13:10

sky


People also ask

What is an example of an operator?

In programming, an operator is a symbol that operates on a value or a variable. Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction.

Is an operator a person?

An operator is a person who is employed to operate or control a machine. ... computer operators. An operator is a person or a company that runs a business.

Who is an operator of a company?

Definition: A Business Operator is the primary force driving a team working towards fulfillment of a company vision. This may be a dedicated team of contractors, but usually includes a mixture of contractors and employees.


2 Answers

You have to wrap it in parentheses:

roles.Contains(u.RoleID.Value) && (u.isValid ?? false)

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.

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

or simpler by using the ==-operator with the bool?:

roles.Contains(u.RoleID.Value) && u.isValid == true
like image 63
Tim Schmelter Avatar answered Sep 21 '22 02:09

Tim Schmelter


Given bool will default to false anyway you could use GetValueOrDefault

roles.Contains(u.RoleID.Value) && u.isValid.GetValueOrDefault()

Note - GetValueOrDefault does not appear to be supported by EF - see ticket

like image 22
James Avatar answered Sep 18 '22 02:09

James