pistacchio
pistacchio

Reputation: 58863

Linq: assign variables in Lambda expressions

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 
    }
);

Upvotes: 8

Views: 7899

Answers (1)

Atanas Korchev
Atanas Korchev

Reputation: 30661

This should work:

var result = list.Select(a =>
  {
    var localVariable = a.number + 2;
    return new 
    {
        Variable = localVariable 
    };
  }
);

Upvotes: 17

Related Questions