Caio Morais
Caio Morais

Reputation: 29

LINQ C# Join with Left-Join result

I'm trying to do a left-join with the result of another left-join but in some cases it returns me null reference error (obviously), is there any way to do this without using foreach after select?

var result = from f in foo
             from ex in exp.Where(w => w.id == f.idFoo).DefaultIfEmpty()
             from te in tes.Where(w => w.id == ex.anyID).DefaultIfEmpty()
select new
{
    var1 = f.something,
    ...
    var2 = te.anything
};

Upvotes: 1

Views: 193

Answers (2)

Shaun Luttin
Shaun Luttin

Reputation: 141742

That's happening because DefaultIfEmpty is returning a sequence with a single null element. Then you are trying to access properties on a null element.

Use the overload of DefaultIfEmpty to return a non-null default value (of the appropriate data type):

var result = from f in foo
             from ex in exp.Where(w => w.id == f.idFoo)
                           .DefaultIfEmpty(new Exp())
             from te in tes.Where(w => w.id == ex.anyID)
                           .DefaultIfEmpty(new Tes())
select new
{
    var1 = f.something,
    ...
    var2 = te.anything
};

That way you won't be trying to access properties on null elements.

Edit based on comments. In the query, one place that null elements arise is when a Where results in zero matches. For instance, in the third from the ex variable might be a sequence of one null element, and again in the select the te might also be such a sequence. In both cases, accessing a property will throw an exception.

Alternatively, you could do a null test every time you are going to access a property. That would become verbose fast.

Upvotes: 1

AD.Net
AD.Net

Reputation: 13409

Something like this:

var2 = te != null ? te.anything : null

Upvotes: 0

Related Questions