LINQ statement as if condition
I saw a piece of code which was written like this:
if (from n in numbers select n where开发者_如何学Python 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
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
}
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
.
if requires boolean expression. Try with boolean expression in select part.
精彩评论