Your first request is equivalent to this:
MyLinqToSQLTable.Where(x => { return x.objectID == paramObjectID; }).ToList();
The return keyword is missing here. This is necessary when the lambda body is an explicit block, not an expression.
The specification formally defines a lambda expression in a grammar, for example:
lambda expression:
anonymous function-signature => anonymous-function-body
anonymous body function:
expression
block
The first case (expression) is applied when the body does not start with the left brace. The last case (block) is defined as a series of statements (just like the body of a method). As elsewhere in C #, expression statements in a block are limited to declarations, assignments, function calls, increments and decrements. Simply applying the == operator to pair identifiers is not an expression of a valid operator. The second problem is that when the type of the returned method (anonymous or not) is not void , all code paths reaching the end of the block must return a value. Therefore, even if your lambda body was syntactically valid without the return statement, your lambda would be convertible to Action<T> , and not the Func<T, bool> that the Where method expects.
Update:
The problem is the implied return that was there when I just made a logical comparison, now not done. Return (x.objectID == paramObjectID); also not accepted.
Of course, the option x => { return x.objectID == paramObjectID; } x => { return x.objectID == paramObjectID; } your lambda expression is only possible when it needs to be converted to an anonymous method , and not to an expression tree. That is, a lambda with a block body does not convert to Expression<T> . That's why you can use it in LINQ to Objects (where Where takes Func<T, bool> ), but you cannot use it in LINQ to SQL (where Where takes Expression<Func<T, bool>> ).
Mehrdad afshari
source share