FloatLeft
FloatLeft

Reputation: 1337

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
        };

Upvotes: 1

Views: 680

Answers (1)

Doctor Jones
Doctor Jones

Reputation: 21664

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

Upvotes: 2

Related Questions