Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left outer join in LINQ

Tags:

c#

linq

The following piece of code keeps giving me an error message of:

Object reference not set to an instance of an object

var partsWithDefaults =
    from partsList1 in p
    join partsList2 in d on 
    new {   PartNo = partsList1.PartNumber, 
            Rev = partsList1.Revision }
    equals
    new {   PartNo = partsList2.PartNumber, 
            Rev = partsList2.Revision } into joinedLists
    from partDefaults in joinedLists.DefaultIfEmpty()
    select new Part()
    {
        PartNumber = partsList1.PartNumber,
        Revision = partsList1.Revision,
        Description = partsList1.Description,
        UoM = (partDefaults.UoM == null) ? "Null" : partDefaults.UoM,
        ABC = (partDefaults.ABC == null) ? "Null" : partDefaults.ABC            
    };

partsList1 is the master list which contains the PartNumber, Revision and Description fields. partsList2 contains the PartNumber and Revision fields (to join on) and also some supplemental fields (2 examples in code are UoM and ABC). There may not be an item in partsList2 for every item in partsList1 hence the need for a left outer join.

p and d are of type List<Part>.

How can this be fixed?

like image 950
sparkymark75 Avatar asked Dec 28 '25 03:12

sparkymark75


1 Answers

If joinedLists is empty, partDefaults will be null, so you can't dereference it. Try this:

UoM = partDefaults == null ? "Null" : partDefaults.UoM ?? "Null",
ABC = partDefaults == null ? "Null" : partDefaults.ABC ?? "Null",

(as the last two bits of your projection).

Note that this copes with either partDefaults being null or the relevant property being null.

like image 87
Jon Skeet Avatar answered Dec 30 '25 18:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!