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?
Syntax: int Count<TSource>(); Count<TSource>(Func<TSource, bool> predicate): This method is used to return the number of items which satisfy the given condition. The return type of this method is System.
In its simplest form (without any parameters), the Count() method returns an int indicating the number of elements in the source sequence. IEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" }; // Will return 4 int result = strings. Count();
Alternatively, to get the count of a single element, filter the list using the Where() method to obtain matching values with the specified target, and then get its count by invoking the Count() method. That's all about getting the count of the number of items in a list in C#.
use . ToArray() or . ToList() to get it as a countable object. The reason it returns an IEnumerable is because it doesn't execute your selects/filters until you try to do something with it (like foreach over it).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With