0

I get an 'object reference not set' with this kind of code below. Problem occurs when I add the DefaultIfEmpty() to make a left join. But I need to see in report that there is no PLACE for the 4th item of lst1.

How can I obtain a line where PLACE is null? Here is my code example from LinqPad.

If you uncomment the line : new ID (){id1 = 10152 , id2 = null} you get the error.

var Lst1  = new List<ID>
{
    new ID (){id1 = 10152 , id2= 250},
    new ID (){id1 = 10152 , id2 = 1},
    new ID (){id1 = 10152 , id2= 106},
    //new ID (){id1 = 10152 , id2 = null}
};
var Lst2 = new List<STORE>
{
    new STORE () {sto1 = 10152 , sto2 = "General Store"}
};
var Lst3 = new List<PLACE>
{
    new PLACE () {pla1 = 250 , pla2 = "London"},
    new PLACE () {pla1 = 1 , pla2 = "Paris"},
    new PLACE () {pla1 = 106 , pla2 = "Miami"}
}; 

var regsup =
            (from l in Lst1
             join st in Lst2 on l.id1  equals  st.sto1
             join pl in Lst3 on l.id2 equals pl.pla1 into pll
             from plll in pll.DefaultIfEmpty()
                select new
                {
                    StoID = st.sto1,
                    Store = st.sto2,
                    PlaceID = plll.pla1,
                    Place = plll.pla2                  
                }).Distinct();
                regsup.Dump();
}
class ID
{
    public decimal id1 { get; set; }
    public decimal? id2 { get; set; }
}
class STORE
{
    public decimal sto1{ get; set; }
    public string sto2{ get; set; }
}
class PLACE
{
    public decimal pla1{ get; set; }
    public string pla2{ get; set; }
}
Matt Rowland
  • 4,575
  • 4
  • 25
  • 34
GYCO50
  • 45
  • 1
  • 8
  • Yes I found some similar examples but never when beginning the query with a list. Question has been solved hereunder by Chris. Use of the ternary on the source itsef (plll) is the solution. Linqpad is also the plus of this question. Thanks to everybody. G. – GYCO50 Jun 19 '16 at 08:30

1 Answers1

2

You will need to check to make sure plll is not null before accessing any of it's properties. DefaultIfEmpty() returns a default object which in this case will be null.

Your select statement needs to be:

                select new
                {
                    StoID = st.sto1,
                    Store = st.sto2,
                    PlaceID = plll != null ? plll.pla1 : 0,
                    Place = plll != null ? plll.pla2 : ""
                }).Distinct();

Or if using C# 6 you can just have:

PlaceID = plll?.pla1,
Place = plll?.pla2
ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • Thanks Chris, exactly what I wanted ! I tried before with this ternary condition but at the wrong place. Solution is effectively to check on plll and not pll.pla1! Great for the c#6 itp. I will quickly move on this. .Regards.Guy – GYCO50 Jun 19 '16 at 08:21