The operator '&&' cannot be applied to operands of type 'bool' and 'bool?'

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 role is in role (1, 2), hence above line
// and also I need to get user who 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 where does the item I need to get the user who is in the role (1,2) && & isValid == true if isValid is 'null' makes it false. thank

+6
source share
3 answers

You must enclose it in brackets:

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

a bit confused with (u.isValid ?? false), does this mean that if u.isValid == null then make it false and look for users for whom u.isValid is false, this is not what I want .

, , nulls false , isValid null false. , ?? -operator Nullable<bool> bool, &&. , , :

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

== -operator bool? :

roles.Contains(u.RoleID.Value) && u.isValid == true
+20

, bool false, GetValueOrDefault

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

. GetValueOrDefault EF - .

+6

You can try this.

 foreach (var user in dataContext.Users
          .Where(u => roles.Contains(u.RoleID.Value) 
             && (u.isValid ?? false))) // note the bracket around (u.isValid ?? false)

Or

foreach (var user in dataContext.Users
       .Where(u => roles.Contains(u.RoleID.Value) 
        && (u.isValid.HasValue && u.isValid))) //you can use HasValue to check for null
+2
source

All Articles