Click here to Skip to main content
15,889,867 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Hi,
I have 2 type's of codes that use datatable in order to evaluate
a string like "2+3/4" and return the result.
I'm looking for a way to modify them so i can evaluate a string
with variable's so i can read new data from the user in runtime, like "2+X/4"
when X is assigned with some number before.

first code type uses datatable.compute:

C#
using (DataTable eval = new DataTable())
{
    //Evaluate the Arithmetic expression
    var result = eval.Compute("1+2*3/4", null);

    //Displaying the result
    Console.WriteLine("Result: {0} of Type: {1}", result, result.GetType().Name);
}


second code:
C#
static double Evaluate(string expression) {
  var loDataTable = new DataTable();
  var loDataColumn = new DataColumn("Eval", typeof (double), expression);
  loDataTable.Columns.Add(loDataColumn);
  loDataTable.Rows.Add(0);
  return (double) (loDataTable.Rows[0]["Eval"]);
}


doesnt matter to me which code to use.
I cant use third party projects like Ncalc,IT department doesnt allow it.
Posted
Updated 9-Feb-13 7:57am
v2
Comments
Sergey Alexandrovich Kryukov 9-Feb-13 13:37pm    
Why?!
—SA

1 solution

Using your first option
C#
string X = "4";             // or however you are assigning "some number before"
string uinput = "1+2*3/X";  // or whatever the user has input

string expr = uinput.Replace("X", X);       // Do the variable substitutions

var result = eval.Compute(expr, null);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900