Reputation: 1643
I have a List
of "widget"s (which have an int ID), and a List
of selected IDs. My end goal is to have a List of hydrated widgets that agrees with the ID list inside my "set".
public List<Widget> widgets { get; set; }
public List<int> widgetIds
{
get
{
return widgets.Select(x => x.widgetId).ToList();
}
set
{
foreach (int addId in value.Except(widgets.Select(x => x.widgetId)))
{
widgets.Add(_dbWidgetHelper.getWidget(addId));
}
//I need to invert the add somehow
}
}
I've been trying everything I can think of using RemoveAll
and Except
, but I can't wrap my head around the solution yet. I know this can be done in one line, but the closest I've got is:
var removeIds = widgets.Select(x => x.widgetId).Except(value);
//this is me trying anything I can think of... obviously a syntax error.
widgets.RemoveAll(x=>x.widgetId in removeIds);
Upvotes: 0
Views: 67
Reputation: 754735
Try the following. Note that I changed removeIds
to be a HashSet<int>
to prevent the query from being re-evaluated every time and to make the look up faster
var removeIds = new HashSet<int>(widgets.Select(x => x.widgetId).Except(value));
widgets.RemoveAll(x => removeIds.Contains(x.widgetID));
Upvotes: 2