GurdeepS
GurdeepS

Reputation: 67223

LINQ statement as if condition

I saw a piece of code which was written like this:

if (from n in numbers select n where n = 5)

However, I tried writing something like this but came across errors (bare in mind the code sample may not be exactly as above as I am typing from memory). How can I write code like the above?

Thanks

Upvotes: 1

Views: 529

Answers (3)

Matej
Matej

Reputation: 7627

if requires boolean expression. Try with boolean expression in select part.

Upvotes: 0

SLaks
SLaks

Reputation: 887453

It was probably something like this:

if ((from n in numbers where n == 5 select n).Any())

This can also be written as

if (numbers.Any(n => n == 5))

It is possible, but highly unlikely, that the code was actually

if (from n in numbers where n == 5 select n)

and numbers was a custom non-enumerable type with a Select method that returns bool.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564413

In order to use this as a condition, you need to have an expression that returns a boolean. Most likely, this means checking to see if there are any numbers that meet your criteria.

You probably wanted to do:

if ( (from n in numbers where n == 5 select n).Any() )
{
   // Do something
}

Personally, I'd avoid the language integrated syntax, and write this as:

if (numbers.Where(n => n == 5).Any())
{
   // Do something
}

Or even:

if (numbers.Any(n => n == 5))
{
   // Do something
}

Upvotes: 3

Related Questions