LINQ NullReferenceException by defaultIfEmpty

I am looking for a solution to the problem when the DefaultIfEmpty() extension method does not select null values ​​when used in an external LINQ connection.

Enter the code as follows:

  var SummaryLossesWithNets = (from g in SummaryLosses join n in nets on g.Year equals n.Year into grouping from x in grouping.DefaultIfEmpty() select new { Year = g.Year, OEPGR = g.OccuranceLoss, AEPGR = g.AggregateLoss, OEPNET = ((x.OEPRecovery == null) ? 0 : x.OEPRecovery), AEPNET = ((x.AEPRecovery == null) ? 0 : x.AEPRecovery), }); 

There are many years of data in the SummaryLosses list that I want to join the "network" table, which contains part of the parts of the year. An exception is thrown when x is a null value, I assume that years in SummaryLosses that do not correspond to years in the networks create null values ​​in the grouping list.

How to check the null value here? As you can see, I tried to check the null value on the properties of x, but since x is null, this will not work.

Regards Richard

+6
source share
2 answers

Just check if x is null:

 OEPNET = x == null ? 0 : x.OEPRecovery, AEPNET = x == null ? 0 : x.AEPRecovery 

Or if x.OEPRecovery and x.AEPRecovery are also null-value properties, use:

 OEPNET = x == null ? 0 : (x.OEPRecovery ?? 0), AEPNET = x == null ? 0 : (x.AEPRecovery ?? 0) 
+7
source

If you have a lot of connection statements

check the verification of all joined tables and make sure that foreign key you are using (in comparison or say Interested) is not null

0
source

All Articles