如果在Lambda C#中为null,则为默认值

时间:2018-12-01 04:38:28

标签: c# lambda

我正在尝试使用lambda表达式连接三个表。如果两个表必须相互匹配,则下面的代码有效,但是如果存在与其他表不对应的记录,则会返回错误。Object reference not set to an instance of an object.

using (WeeklyCreditEntities WCE = new WeeklyCreditEntities())
        {
            var xx = Raw.GroupJoin(WCE.tblCHRIS,
                                a => a.CHRISID,
                                b => b.CHRISID,
                                (a, b) => new
                                {
                                    raw = a,
                                    chris = b.DefaultIfEmpty().FirstOrDefault()
                                }).Select(x => new
                                {
                                    RawEMpid = x.raw.EmployeeID,
                                    CHRISEmpID = x.chris.EmployeeID,
                                    RawCHRISID = x.raw.CHRISID,
                                    RawFullname = x.raw.Fullname,
                                    RawAmount = x.raw.Amount,
                                    chrisBank = x.chris.BankAccount
                                }).ToList();

1 个答案:

答案 0 :(得分:2)

您可以将安全导航运算符与null-coalescing运算符一起使用:

using (WeeklyCreditEntities WCE = new WeeklyCreditEntities())
{
    var xx = Raw.GroupJoin(WCE.tblCHRIS,
        a => a.CHRISID,
        b => b.CHRISID,
        (a, b) => new
        {
            raw = a,
            chris = b.DefaultIfEmpty().FirstOrDefault()
        }).Select(x => new
        {
        RawEMpid = x.raw?.EmployeeID ?? defaultValue,
        CHRISEmpID = x.chris?.EmployeeID ?? defaultValue,
        RawCHRISID = x.raw?.CHRISID ?? defaultValue,
        RawFullname = x.raw?.Fullname ?? defaultValue,
        RawAmount = x.raw?.Amount ?? defaultValue,
        chrisBank = x.chris?.BankAccount ?? defaultValue
        }).ToList();

或者,如果您使用的是旧版本的C#/ Visual Studio,则可以使用三元运算符:

using (WeeklyCreditEntities WCE = new WeeklyCreditEntities())
{
    var xx = Raw.GroupJoin(WCE.tblCHRIS,
        a => a.CHRISID,
        b => b.CHRISID,
        (a, b) => new
        {
            raw = a,
            chris = b.DefaultIfEmpty().FirstOrDefault()
        }).Select(x => new
        {
        RawEMpid = x.raw != null? x.raw.EmployeeID : defaultValue,
        CHRISEmpID = x.chris != null? x.chris.EmployeeID : defaultValue,
        RawCHRISID = x.raw != null? x.raw.CHRISID : defaultValue,
        RawFullname = x.raw != null? x.raw.Fullname : defaultValue,
        RawAmount = x.raw != null? x.raw.Amount : defaultValue,
        chrisBank = x.chris != null?x.chris.BankAccount : defaultValue
        }).ToList();