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,002
  • 18
  • 79
  • 121

7 Answers7

8
p.bazNullable.GetValueOrDefault()
gsharp
  • 26,016
  • 21
  • 83
  • 126
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
  • 62,367
  • 15
  • 124
  • 190
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
  • 103,479
  • 23
  • 206
  • 257
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,454
  • 2
  • 24
  • 40
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
  • 34,403
  • 40
  • 131
  • 186
0

you could just do:

var list = db.Bars.Where(p => p.baz && p.bazNullable != null && p.bazNullable == true);
ub1k
  • 1,646
  • 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
  • 35,718
  • 7
  • 75
  • 81
  • 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