tags:

views:

434

answers:

1

Hi,

I am attempting to select from a List using a linq expression where the range variable is evaluated in a static method that returns boolean. I would like to select the range variable that returns true when the range variable is evaluated using the method.

var result = from rangeVariable in DataSource
             where (rangeVariable => Foo.MethodReturnsBoolean(rangeVariable) == true)
             select rangeVariable;

I get this error:

Cannot convert Lambda Expression to type 'bool' because it is not a delegate type.

Can anyone explain what is going on, and how I could achieve this?

+12  A: 

You don't need the lambda expression in the "where" clause - the query expression translation does that for you. Just use:

var result = from rangeVariable in DataSource
             where Foo.MethodReturnsBoolean(rangeVariable) == true
             select rangeVariable;

I would personally then remove the "== true" redundancy (I know this was only sample code, but...):

var result = from rangeVariable in DataSource
             where Foo.MethodReturnsBoolean(rangeVariable)
             select rangeVariable;

I'd then consider what using a query expression is actually buying you. If you're just doing a "where" (or just doing a "select") you may find dot notation simpler:

var result = DataSource.Where(x => Foo.MethodReturnsBoolean(x));

It gets even better though: the compiler doesn't need to infer a return value from the lambda expression (because it will always be bool) so you can just use a method group conversion:

var result = DataSource.Where(Foo.MethodReturnsBoolean);

How much cleaner is that? :)

Jon Skeet
Very! Thanks Jon!
theringostarrs
+1 I'll answer that after my head stops spinning ;)
Gishu