foreach(var category in categories) {
a.AddRange(_db.Articles.Where(c => c.Categories.Contains(category)));
}
The code runs fine, yet I get a warning about “access to modified closure” in reference to category used in the lambda expression.
Question: Is the warning of any consequence in this circumstance?
The warning here is because you are accessing the variable
categoryinside the closure for theWherelambda. The valuecategorychanges with every iteration andWhereis delay executed hence it will see the current value ofcategoryvs. the value at the time the lambda was created.In this case you are likely fine. Even though
Whereis delay evaluated theAddRangemethod is prompt and will force the evaluation ofWhereto completion. Hence theWheremethod will see the value ofcategoryit expects.If you’d like to remove the warning though simply declare a local copy of the iteration variable and capture that instead.