简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM