简体   繁体   中英

Using LINQ to perform a left outer join

I'm trying to build a list that contains all the objects from one list but updates a specific property if the object exists in another list.

Firstly I create a List of all the possible "Options". I then want to update the "Selected" property of any items in this list that also exist in another list of "Options" that I have created. I was hoping the code below would work but I'm getting the exception "Object reference not set to an instance of an object".

        var query = from o in AllOptions
                    join so in SelectedOptions on o.Code equals so.Code into newOptions
                    from no in newOptions.DefaultIfEmpty()
                    select new Option
        {
            Name = o.Name,
            Description = o.Description,
            Code = o.Code,
            Applicable = o.Applicable,
            Selected = no.Selected
        };

You're getting the exception from the no.Selected statement in your projection, when no is null it will throw because you're dereferencing a null.

You can fix it by specifying a default value when no is null:

//default to false when no is null
Selected = (no == null) ? false : no.Selected

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