Alex Rivera | Logout

Converting lambda expression into an expression tree

Asked 2011-12-07T18:10:49.277
8

From C# in depth:

Not all lambda expressions can be converted to expression trees. You can’t convert a lambda with a block of statements ( even just one return statement ) into an expresion tree --> it has to be in the form that just evaluates a single expression.

Since Linq-to-Object statements don't get converted into expression tree objects, the lambda expressions used with Linq-to-Object operators can contain a block of statements

        string[] count = { "one ", "two ", "three ", "four ", "five ", "six " };
        IEnumerable<int> result = count.Select(item =>
                               {
                                   Console.WriteLine(item);
                                   return item.Length;
                               });
        foreach (int i in result);

OUTPUT:

one two three four five six

I haven't yet started learning Linq-To-Sql or Linq-To-Entities, but I assume lambda expressions used with LINQ statements that operate on IQueryable<T> can only ever contain a single expression, due to restristion that only a single expression can be converted into an expression tree?

Thank you

Edit
Report

1 Answer

1

You are correct, they can only ever contain a single expression.

answered 2011-12-07T18:17:09.667

Your Answer