How to count the number of elements that match a condition with LINQ

前端 未结 5 1008
遇见更好的自我
遇见更好的自我 2020-11-29 12:09

I\'ve tried a lot of things but the most logical one for me seems this one:

int divisor = AllMyControls.Take(p => p.IsActiveUserControlChecked).Count();
<         


        
5条回答
  •  误落风尘
    2020-11-29 12:29

    The parameter for Take requres an int and you are passing in a delegate/ lambda expression. Take is designed to just take the first count of the elements.

    You can use the Count method and pass in a delegate to count the elements that fit its criteria. This way you only iterate the IEnumerable once, rather than first culling out the ones that don't fit your criteria, and then again to actually count them.

    AllMyControls.Count(p => p.IsActiveUserControlChecked);
    

提交回复
热议问题