I need to iterate over a List of objects, doing something only for the objects that have a boolean property set to true. I\'m debating between this code
for
Actually, it's not "looping twice." The .Where clause uses deferred execution. In other words, practically no work is performed when you call .Where, but when you iterate over the result, it will iterate over the original list and only pass through items that match your condition. If you think of it in terms of how the code gets executed, you're effectively doing this:
Func matchesCondition = p => p.Condition;
foreach(var parameter in parameters)
{
if(matchesCondition(parameter))
{
...
}
}
As a matter of style, I personally prefer something more like:
var matchingParameters = parameters.Where(p => p.Condition);
foreach(var parameter in matchingParameters)
{
}