LINQ + Foreach vs Foreach + If

前端 未结 4 1616
醉梦人生
醉梦人生 2020-12-02 09:55

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         


        
4条回答
  •  我在风中等你
    2020-12-02 10:13

    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)
    {
    }
    

提交回复
热议问题