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};
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();
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();
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
orMax
, 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.
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