theringostarrs
theringostarrs

Reputation: 12410

Linq Evaluating a method as a lambda expression

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?

Upvotes: 3

Views: 2794

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503869

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? :)

Upvotes: 18

Related Questions