8

when using the "from.. select" form I can assign local variables in Linq with the let statement. How to capture variables with lambdas? Non working example of what I need:

var result = list.Select(a =>
    let localVariable = a.number + 2 // <- obviously non working
    new {
        Variable = localVariable 
    }
);

1 Answer 1

17

This should work:

var result = list.Select(a =>
  {
    var localVariable = a.number + 2;
    return new 
    {
        Variable = localVariable 
    };
  }
);
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Yep, just stick a ; on the end of "var localVariable = a.number + 2"
thanks i think this is what i'm looking for, but i get the following error: A lambda expression with a statement body cannot be converted to an expression tree
You didn't state you were using Linq on an IQueryable. What provider are you using? EF? Linq-to-sql? Or something else?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.