开发者

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

开发者 https://www.devze.com 2023-03-18 00:44 出处:网络
This can\'t compile: void Foo() { using (var db = new BarDataContext(ConnectionString)) { // baz is type \'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 clea开发者_开发问答n 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));


you could just do:

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


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


How about this

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

OR

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

精彩评论

暂无评论...
验证码 换一张
取 消