Technically, you do not need to enumerate your data in a loop in order to make it work (although it is one of the ways to fix the problem). The reason why it does not work without the ToList
is that the code in the inner Where
refers to a modified closure - variable ap
which is modified in a loop.
Using a temporary variable for it would fix the problem:
IEnumerable<AccessData> reports = _model.GetAllAccessEvents();
foreach (var ap in AccessPoints.Where(x => !x.IsChecked)) {
var theId = ap.Id; // Introduce a temporary variable
reports = reports.Where(x => x.AccessPointId != theId);
}
Another solution would be using a Where
that compares AccessPointId
s to all items in the access events without a loop, like this:
reports = _model
.GetAllAccessEvents()
// The condition ensures that x is such that its ID is not present
// among the AccessPointIds of the checked access points:
.Where(x => !AccessPoints.Any(ap => ap.IsChecked && ap.AccessPointId == x.Id));