简体   繁体   中英

Lambda expression with <bool> and System.Nullable<bool>

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?

p.bazNullable.GetValueOrDefault()

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.

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)

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

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

you could just do:

var list = db.Bars.Where(p => p.baz && p.bazNullable != null && p.bazNullable == true);

How about this

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

OR

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM