2

When declaring a parameter expression, for example:

ParameterExpression x = Expression.Parameter(typeof(double),"x");

You can then use this parameter to construct Lambda expressions:

Expression Lowerbound = Expression.Constant(0.0,typeof(double));

Expression GreaterThanorEqual = Expression.GreaterThanOrEqual(x, Lowerbound);

Expression TestExpression = Expression.Lambda(GreaterThanorEqual,x);

Console.WriteLine(TestExpression.ToString());

    // returns x => (x >= 0)

I now need a way to construct expressions of the form

x => (x[0] >= 0)
x => (x[1] >= 0)
x => (x[2] >= 0)
... et cetera

I cannot, however, find a way to define a parameter

Expression.Parameter(typeof(double[]),"x");

array as one Parameter

and then

Expression.Parameter(typeof(double),"x["+i+"]");

As another

is there a way to define a Parameter that has a Type of double[] ?

1
  • Your Parameter call should work, are you asking how to construct the index expression? Expression.ArrayAccess(xParam, Expression.Constant(0)) should work. Commented Aug 21, 2017 at 16:58

1 Answer 1

2

In order to access an array during the expression use Expression.ArrayIndex. This takes two parameters: 1) the array to get an item from, 2) the index to pass into the array.

The following code should compile the expression into a delegate, which takes double[] array, and int index in order to perform the x => x[i] >= 0 expression.

var arrayParam = Expression.Parameter(typeof(double[]), "x");
var indexParam = Expression.Parameter(typeof(int), "i");

var left = Expression.ArrayIndex(arrayParam, indexParam);
var right = Expression.Constant(0.0, typeof(double));

var body = Expression.GreaterThanOrEqual(left, right);

// Create and compile a lambda expression into a delegate to perform:
// x => x[i] >= 0
var func = Expression.Lambda<Func<double[], int, bool>>(body, arrayParam, indexParam)
    .Compile();

double[] data = new double[] { -2.0, -1.0, 0.0, 1.0, 2.0, 3.0 };

for (int i = 0; i < data.Length; i++)
{
    var d = data[i];
    var x = func(data, i);
    Console.WriteLine($"i: {d} => {x}");
}
Sign up to request clarification or add additional context in comments.

Comments

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.