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

前端 未结 5 1012
遇见更好的自我
遇见更好的自我 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:28

    Why not directly use Count? That == true statement is also highly redundant.

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

    Also, you are getting an error on your Take method because it is waiting for an int. You need to specify the number of contiguous elements from the start of the collection you want to get, you cannot put a lambda expression. You need to use TakeWhile for that. So

    int divisor = AllMyControls.TakeWhile(p => p.IsActiveUserControlChecked == true).Count();
    

    would have been correct, but would not work the way you expect it; it stops once the condition is broken. So if AllMyControls contains true, true, false, true, TakeWhile with Count will return 2 instead of your expected 3.

提交回复
热议问题