2

This can't compile:

void Foo()
{
    using (var db = new BarDataContext(ConnectionString))
    {
        // baz is type 'bool'
        // bazNullable is type 'System.Nullable<bool>'
        var list = db.Bars.Where(p => p.baz && p.bazNullable); // Compiler: 
            // Cannot apply operator '&&' to operands of type
            // 'System.Nullable<bool> and 'bool'
    }
}

Do I really have to make this through two runs, where I first use the as condition and then run through that list with the nullable conditions, or is there a better clean smooth best practice way to do this?

radbyx
  • 9,352
  • 21
  • 84
  • 127

7 Answers7

8
p.bazNullable.GetValueOrDefault()
gsharp
  • 27,557
  • 22
  • 88
  • 134
5

Something like this?

 db.Bars.Where(p => p.baz && p.bazNullable.HasValue && p.bazNullable.Value);

I don't know if Linq-to-Sql can handle it.

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
4

There are two issues here:

The shortcircuiting && is not supported on nullable types for some reason. (Related Why are there no lifted short-circuiting operators on `bool?`?)

The second is that even if it were supported by C#, your code still makes no sense. Where needs a bool as result type of your condition, not a bool?. So you need to decide how the case where baz==true and bazNullable==null should be treated.

This leads to either p.baz && (p.bazNullable==true) or p.baz && (p.bazNullable!=false) depending on what you want.

Or alternatively p.baz && (p.bazNullable??false) or p.baz && (p.bazNullable??true)

Community
  • 1
  • 1
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
1

You're trying to apply a logical && operation to a nullable bool.

If you are sure that p.bazNullable is not null, then you can try

var list = db.Bars.Where(p => p.baz && p.bazNullable.Value);

or if a null value equates to false, then try

var list = db.Bars.Where(p => p.baz && p.bazNullable.ValueOrDefault(false));
Neil Moss
  • 6,598
  • 2
  • 26
  • 42
0

use:

  var list = db.Bars.Where(p => p.baz && p.bazNullable.Value);

To handle null exceptions use:

  var list = db.Bars.Where(p => p.baz && p.bazNullable != null && p.bazNullable.Value);
Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188
0

you could just do:

var list = db.Bars.Where(p => p.baz && p.bazNullable != null && p.bazNullable == true);
ub1k
  • 1,674
  • 10
  • 14
0

How about this

Where(p => p.baz && (p.bazNullable ?? false));

OR

Where(p => p.baz && (p.bazNullable ==null ? false : p.bazNullable.Value));
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
  • Might it be safer to use nullable HasValue instead of checking for just nulls? Example: Where(p => p.baz && (p.bazNullable.HasValue && p.bazNullable.Value)); – Ben Clark-Robinson Aug 02 '11 at 07:12