The warning here is because you are accessing the variable category
inside the closure for the Where
lambda. The value category
changes with every iteration and Where
is delay executed hence it will see the current value of category
vs. the value at the time the lambda was created.
In this case you are likely fine. Even though Where
is delay evaluated the AddRange
method is prompt and will force the evaluation of Where
to completion. Hence the Where
method will see the value of category
it expects.
If you'd like to remove the warning though simply declare a local copy of the iteration variable and capture that instead.
foreach(var category in categories) {
var localCategory = category;
a.AddRange(_db.Articles.Where(c => c.Categories.Contains(localCategory)));
}