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
category
inside the closure for theWhere
lambda. The valuecategory
changes with every iteration andWhere
is delay executed hence it will see the current value ofcategory
vs. the value at the time the lambda was created.In this case you are likely fine. Even though
Where
is delay evaluated theAddRange
method is prompt and will force the evaluation ofWhere
to completion. Hence theWhere
method will see the value ofcategory
it expects.If you'd like to remove the warning though simply declare a local copy of the iteration variable and capture that instead.
It tells you that the "category" variable lives in closure and can be modified outside your LINQ expression.
Look at the question here for some explanation.