Return from linq where statement

I have the following link function

MyLinqToSQLTable.Where(x => x.objectID == paramObjectID).ToList(); 

In most cases, you can change the linq call to multiple lines by adding curly braces around the body of the method. Like this:

 MyLinqToSQLTable.Where(x => { x.objectID == paramObjectID; }).ToList(); 

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.

How to do it? I can do it?

NOTE. I know that I can add another where clause if necessary. But I would still like to know the answer to this question.

+6
c # linq linq-to-objects linq-to-sql
source share
3 answers

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>> ).

+8
source share

It works?

 MyLinqToSQLTable.Where(x => { return x.objectID == paramObjectID; }).ToList(); 
+1
source share
 MyLinqToSQLTable.Where(x => { return x.objectID == paramObjectID; }).ToList(); or MyLinqToSQLTable.Where(x => { return x.objectID == paramObjectID; }).ToArray(); 
-one
source share

All Articles