Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: assign variables in Lambda expressions

Tags:

c#

linq

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 
    }
);
like image 250
pistacchio Avatar asked Mar 03 '11 09:03

pistacchio


1 Answers

This should work:

var result = list.Select(a =>
  {
    var localVariable = a.number + 2;
    return new 
    {
        Variable = localVariable 
    };
  }
);
like image 110
Atanas Korchev Avatar answered Nov 15 '22 21:11

Atanas Korchev