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
精彩评论