Zander Fick Zander Fick -3 years ago 112
C# Question

Build and assign Lambda expression iteratively

Consider the following:

var Constraints = new NonlinearConstraint[2*nVars];

var Constraints = new[] {
new NonlinearConstraint(nVars, x => x[0] >= 0),
new NonlinearConstraint(nVars, x => x[0] <= 1),
new NonlinearConstraint(nVars, x => x[1] >= 0),
new NonlinearConstraint(nVars, x => x[1] <= 1),
// et cetera for all x[i]

I am tring to find a way to construct this variable using a for loop for all

I am unable to find any proper documentation on this. I have tried using


However I run into a conversion error code

Any ideas or help would be greatly appreciated.

Answer Source

Are you looking for something like this?

Enumerable.Range(0, nVars)
          .SelectMany(i => {
                               var localI = i;
                               return new[]
                                          new NonlinearConstraint(nVars, x => x[localI] >= 0),
                                          new NonlinearConstraint(nVars, x => x[localI] <= 1),

This creates an array of NonlinearConstraints, two for each i from 0 to nVars-1...

That is, you don't create the lambda iteratively, but the array of constraint objects. Each of those has its own lambda, of course...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download