views:

56

answers:

2

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.

+3  A: 

Your first query is equivalent to this one:

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

You are missing the return keyword 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:

lambda-expression:
      anonymous-function-signature => anonymous-function-body

anonymous-function-body:
      expression
      block

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 not void, 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 to Action<T>, and not Func<T, bool> that Where method expects.


Update:

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.

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 to Expression<T>. That's why you can use it in LINQ to Objects (in which Where takes Func<T, bool>) but you can't use it in LINQ to SQL (in which Where takes Expression<Func<T, bool>>).

Mehrdad Afshari
+1  A: 

Does this work?

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