LINQ使用可空值继续加入

时间:2015-08-17 07:52:37

标签: c# linq entity-framework

from t in Tasks
join user in UserInfo on t.Publisher equals user.Account into temp
from userinfo in temp.DefaultIfEmpty()
select new
{
    t.Title,
    IsCertificated = userinfo.IsCertificated
}

有些代码喜欢。 IsCertificated是布尔类型,当userinfo为null时,此查询将不起作用。

  

不为System.Boolean

指定Null值类型

我知道它可以修改:

 select new
    {
        t.Title,
        IsCertificated =userinfo == null?false: userinfo.IsCertificated
    }

但是,我的userinfo有太多非空属性。我如何处置它?

1 个答案:

答案 0 :(得分:0)

您可以将条件运算符拉出对象创建。

from t in Tasks
join user in UserInfo on t.Publisher equals user.Account into temp
from userinfo in temp.DefaultIfEmpty()
select userinfo != null
    ? new
        {
            t.Title,
            IsCertificated = userinfo.IsCertificated
        }
    : new
        {
            t.Title,
            IsCertificated = false
        }
相关问题