带有<bool>和System.Nullable <bool>的Lambda表达式

rad*_*byx 2 c# lambda expression nullable linq-to-sql

这无法编译:

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'
    }
}
Run Code Online (Sandbox Code Playgroud)

我是否真的必须通过两次运行来实现这一点,我首先使用as条件,然后使用可空的条件运行该列表,或者是否有更好的干净顺利的最佳实践方法来执行此操作?

gsh*_*arp 8

p.bazNullable.GetValueOrDefault()
Run Code Online (Sandbox Code Playgroud)


Ste*_*ger 5

像这样的东西?

 db.Bars.Where(p => p.baz && p.bazNullable.HasValue && p.bazNullable.Value);
Run Code Online (Sandbox Code Playgroud)

我不知道Linq-to-Sql是否可以处理它.