I have the following link function
MyLinqToSQLTable.Where(x => x.objectID == paramObjectID).ToList();
I most of the time you can change a linq call to be several lines by adding curly brackets around the method body. Like this:
MyLinqToSQLTable.Where(x =>
{
x.objectID == paramObjectID;
}).ToList();
Problem is the implied return that was there when I just did a Boolean compare is now not done. Return (x.objectID == paramObjectID); is not accepted either.
How do do this? can I do this?
NOTE: I know that I can add another where clause if needed. But I would still like to know the answer to this.
Your first query is equivalent to this one:
You are missing the
returnkeyword here. It’s necessary when the lambda body is an explicit block rather than an expression.The spec formally defines lambda-expression in grammar like:
The former case (expression) applies when the body doesn’t begin with a left curly brace. The latter case (block) is defined as a series of statements (just like a method body). Like other places in C#, expression statements in a block are restricted to declarations, assignments, function call, increment, and decrement. Merely applying operator
==to a couple identifiers doesn’t the expression a valid statement. The second issue is that when the return type of a method (anonymous or not) is notvoid, all code paths reaching the end of the block should return a value. Consequently, even if the body of your lambda was syntactically valid, without a return statement, your lambda would be convertible toAction<T>, and notFunc<T, bool>thatWheremethod expects.Update:
Of course, the
x => { return x.objectID == paramObjectID; }variant of your lambda expression is only possible when it’s supposed to be converted to an anonymous method, not an expression tree. That is, a lambda with a block body is not convertible toExpression<T>. That’s why you can use it in LINQ to Objects (in whichWheretakesFunc<T, bool>) but you can’t use it in LINQ to SQL (in whichWheretakesExpression<Func<T, bool>>).