Vic
Vic

Reputation: 497

Default value if null in lambda C#

I'm trying to join three table using lambda expression. The code below is working if both tables have to match each other but if there are records without corresponding to other table it return error.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();

Upvotes: 0

Views: 1059

Answers (1)

bcwhims
bcwhims

Reputation: 2875

You could use the safe navigation operator with the null-coalescing operator:

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

Or if you're using an older version of C#/Visual Studio, you could just use a ternary operator:

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

Upvotes: 2

Related Questions