.NET Framework - A lambda expression with a statement body cannot be converted to anexpression tree

Asked By Ramkrishnan . on 24-Jan-12 02:08 AM
hi,

i got an error "A lambda expression with a statement body cannot be
converted to an expression tree" when i write below code.

data = is the iquerable object.

how to solve tis error.



data.Where(
item =>
{
object oValue =
item.GetType().GetProperty(field).GetValue(item, null);
IComparable cItem = oValue as IComparable;

switch (comparison)
{
case Comparison.Eq:

switch (type)
{
case FilterType.List:
return !(value as
System.Collections.ObjectModel.ReadOnlyCollection<string>).Contains(oValue.ToString());
case FilterType.String:
return !
oValue.ToString().StartsWith(value.ToString());
default:
return !
cItem.Equals(value);
}

case Comparison.Gt:
return cItem.CompareTo(value) < 1;
case Comparison.Lt:
return cItem.CompareTo(value) >
-1;
default:
throw new
ArgumentOutOfRangeException();
}
}
);




Peter Duniho replied to Ramkrishnan . on 24-Jan-12 03:26 AM
Don't try to convert a lambda expression declared with a statement body to
an expression tree.

You might try to move the code into a method which then is used as the sole
expression within the lambda.  However, in many cases when you do that
you will just run into a different problem: the lambda expression can use
only specific, supported elements, which your separate method undoubtedly
will not be included in.

I am not familiar enough with all the ins and outs of expression trees to
know for sure you will run into that problem, and your post does not really
contain enough context to know for sure anyway.  it is worth a try.  But
do not be surprised if it does not work either.  :)

In the end, the real solution may be simply to implement the query logic in
a different way (i.e. using plain objects rather than LINQ to SQL, for
example).

Pete
Marcel_Müller replied to Ramkrishnan . on 24-Jan-12 05:08 AM
C# does not support arbitrary anonymous functions in LINQ expressions.
You need to define a (private) named function with your function body.

bool ItemPredicate(TypeOfItem item)
{ object oValue =
...
}

data.Where(ItemPredicate)
...


Marcel
Nick Hounsome replied to Ramkrishnan . on 26-Jan-12 02:29 AM
An IQueryable is evaluated in the server and hence can only contain
stuff that maps to things the server can understand (typicaly it must
map to SQL)
You can use your lambda if you first bring the data client side with
ToList() and then use Where() on the resulting IEnumerable.
This overload of WHere takes a delegate rather than an expression
tree.