Question

I have the following code:

model.Attendees.Single(p => p.Value == this.CurrentPerson.PersonId.ToString() && p.Disabled == false).Selected = true;           

The person is disabled so it brings back a null reference when trying to set Selected to true.

Is there a LINQ way of handeling this or should I do an if not null then set value.. I've tried Single and SingleOrDefault

Was it helpful?

Solution

Best is (as commented) to first get the item with SingleOrDefault

var item = model.Attendees.SingleOrDefault(p => p.Value == this.CurrentPerson.PersonId.ToString() && p.Disabled == false);     

And then to check or the item is null and if not use the object like:

if(item != null)
{
    item.Selected = true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top