Zander Fick - 2 months ago 10

C# Question

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

`x[i]`

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

`System.Linq.Expressions.Expression.Lambda<>();`

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),
};
})
.ToArray();
```

This creates an array of `NonlinearConstraint`

s, 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...