Mitten
Mitten

Reputation: 249

lambda equivalent to collection.Count(predicate)

What would be a LINQ query-syntax 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};

Upvotes: 8

Views: 20664

Answers (4)

Terry  H
Terry H

Reputation: 347

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

Upvotes: 0

ajawad987
ajawad987

Reputation: 4672

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

Upvotes: 8

Mike Zboray
Mike Zboray

Reputation: 40838

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.

Upvotes: 2

Andomar
Andomar

Reputation: 238296

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

Upvotes: 3

Related Questions