Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda equivalent to collection.Count(predicate)

Tags:

c#

linq

What would be a lambda expression equivalent for the following code

int[] numbers = { 3, 4, 5, 6, 7, 8 };
int count = numbers.Count(x => x > 5 == true); 

I tried this one, but it didn't compile:

var c = from number in numbers where number > 5 select numbers.Count;

this one didn't compile either:

var c = from number in numbers where number > 5 select new {numbers.Count};
like image 819
Mitten Avatar asked May 19 '13 22:05

Mitten


3 Answers

You're close, just need to wrap the LINQ expression in parenthesis like this:

var c = (from number in numbers where number > 5 select number).Count();
like image 50
ajawad987 Avatar answered Nov 20 '22 09:11

ajawad987


The LINQ style with from and in is called "query syntax":

from row in table where row.col1 < 10 select row.col1

It usually contains fewer lambda expressions than "method syntax":

table.rows.Where(r => r.col1 < 10).Select(r => r.col1)

You can mix them up too. For example, this creates a single group for all rows, and computes the row count. A method call like FirstOrDefault() is required to materialize the value:

int c = (
        from n in numbers 
        where n > 5 
        group n by 1 into g 
        select g.Count()
        ).FirstOrDefault();
like image 27
Andomar Avatar answered Nov 20 '22 07:11

Andomar


What you are talking about is query syntax, and not all LINQ methods have an equivalent in query syntax. The most concise expression is numbers.Count(x => x > 5). From the docs:

Some query operations, such as Count or Max, have no equivalent query expression clause and must therefore be expressed as a method call. Method syntax can be combined with query syntax in various ways.

like image 2
Mike Zboray Avatar answered Nov 20 '22 09:11

Mike Zboray