37

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();

AllMyControls is a Collection of UserControls, what I want to know is how many UserControls have the IsActiveUserControlChecked property set to true.

What I get in VS is:

Cannot convert lambda expression to type 'int' because it is not a delegate type

What's wrong with my expression?

5 Answers 5

83
int divisor = AllMyControls.Where(p => p.IsActiveUserControlChecked).Count()

or simply

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

Since you are a beginner, it would be worthwhile to take a look at Enumerable documentation

2
  • 6
    Even simpler :D int divisor = AllMyControls.Count(p => p.IsActiveUserControlChecked);
    – keyboardP
    Commented Jun 21, 2013 at 20:50
  • 2
    @keyboardP I added this to the answer before your comment, but thanks for the input :) Commented Jun 21, 2013 at 20:51
8

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.

2
  • Yes, actually in my code it has to be !=true, and I like that for clarity. Thanks for the suggestion
    – Sturm
    Commented Jun 21, 2013 at 20:52
  • @Sturm Oh, then you can write !p.IsActiveUserControlChecked instead of != true or == false Commented Jun 21, 2013 at 20:55
1

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);
1

Do not KISS

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

Try

int divisor = AllMyControls.Where(x => x.IsActiveUserControlChecked == true).Count();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.