sparkymark75
sparkymark75

Reputation: 593

Left outer join in 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?

Upvotes: 3

Views: 2265

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500245

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.

Upvotes: 3

Related Questions