0

Possible Duplicate:
How can I evaluate a C# expression dynamically?

I can do this;

int x = 6;
var result = new DataTable().Compute(x + " * 10 / 3", null);

And this;

public delegate double function(double x);
function func = delegate(double x) { return x * 10 / 3; };

So how can i compute like first example and assign it to a delegate like second example?

The goal is doing compute work only once, then use it with many variables.

Community
  • 1
  • 1
previous_developer
  • 10,579
  • 6
  • 41
  • 66
  • 2
    possible duplicate of [How can I evaluate a C# expression dynamically?](http://stackoverflow.com/questions/53844/how-can-i-evaluate-a-c-sharp-expression-dynamically) and [c# convert string expression to a boolean expression](http://stackoverflow.com/questions/5029699/c-sharp-convert-string-expression-to-a-boolean-expression) – Kirk Woll Dec 17 '12 at 18:58
  • You want an inline delegate and not just a class method? – Michael Christensen Dec 17 '12 at 18:59

2 Answers2

1

I would use NCalc for these kind of requirements. For example

NCalc.Expression expr = new NCalc.Expression("x * 10 / 3");
expr.EvaluateParameter += (name, args) =>
    {
        if (name == "x" && somecondition == 1) args.Result = 6;
        if (name == "x" && somecondition == 2) args.Result = 12;
    };
var result = expr.Evaluate();
L.B
  • 114,136
  • 19
  • 178
  • 224
0

You just need to create your method (anonymous or not) that utilizes DataTable.Compute.

Func<double, double> function = x => 
    (double)(new DataTable().Compute(x + " * 10 / 3", null));
Servy
  • 202,030
  • 26
  • 332
  • 449