Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

count

linq

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?

like image 947
Sturm Avatar asked Jun 21 '13 20:06

Sturm


People also ask

How to get Count using LINQ in C#?

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.

How to use Count() in C#?

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

How to get Count of elements in list C#?

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#.

How to get Count of IEnumerable object 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).


1 Answers

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

like image 74
Adriano Carneiro Avatar answered Sep 18 '22 16:09

Adriano Carneiro