Why do I have a NullReferenceException when i am using a IsNull condition?

270 Views Asked by At

I have to join 2 different datatable like with linq:

   // let use Linq
        var DateMarket = from p in IndexPrice.AsEnumerable()
                         join q in TickerPrice.AsEnumerable() on p.Field<DateTime>("DATE") equals q.Field<DateTime>("DATE") into UP
                         from q in UP.DefaultIfEmpty()
                         where p.Field<DateTime>("DATE") != null && !q.IsNull("CHG_PCT_1D")
                         select TestRecap.Rows.Add(p.Field<DateTime>("DATE"), q.Field<Double>("CHG_PCT_1D")) ;

however even if I use the condition :

  where p.Field<DateTime>("DATE") != null && !q.IsNull("CHG_PCT_1D")

I still have a NullReferenceException at this line. Do you have an idea why ?

Thanks

2

There are 2 best solutions below

0
On

One among p and q might be null for row after join. Check for their nullification.

where p!=null 
   && p.Field<DateTime>("DATE") != null 
   && q != null 
   && !q.IsNull("CHG_PCT_1D")
0
On

The from q in UP.DefaultIfEmpty() indicates, that if no matching q is found for your p, it will use the default value, which is null (same as with FirstOrDefault() and SingleOrDefault() functions).

Check for q != null, and it should work.