3

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?

1 Answer 1

18

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

Sign up to request clarification or add additional context in comments.

2 Comments

When I tried var = from rangeVariable in Datacontext.table where me.MethodThatReturnsBoolean(rangeVariable) select rangeVariable I got a RUNTIME NotSupportedException: Method 'Boolean MethodThatReturnsBoolean(System.String)' has no supported translation to SQL. Can any boolean function go in a where clause? Any suggestions? stackoverflow.com/questions/8662259/…
@akh2103: It depends on whether you're using LINQ to Objects or LINQ to SQL etc. For LINQ to Objects, you can use any delegate you like - for a translating provider like LINQ to SQL, it has to be an expression tree that the provider knows how to convert.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.