public static double Evaluate(string expression)
{
return (double)new System.Xml.XPath.XPathDocument
(new System.IO.StringReader("<r/>")).CreateNavigator().Evaluate
(string.Format("number({0})", new
System.Text.RegularExpressions.Regex(@"([\+\-\*])").Replace(expression, " ${1} ")
.Replace("/", " div ").Replace("%", " mod ")));
}
In Method 1 System.Text.RegularExpressions.Regex helps in giving space between operator and also to replace "/" operator to div and "%" operator to mod. XPathNavigator.Evaluate method evaluates the string representing an XPath expression and returns the typed result.
Method 2 :
public static double Evaluate(string expression)
{
System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("expression", string.Empty.GetType(), expression);
System.Data.DataRow row = table.NewRow();
table.Rows.Add(row);
return double.Parse((string)row["expression"]);
}
In Method 2 DataColumn.Expression in System.Data.DataTable is used to create a default row with required expression. Thereby DataTable calculate the values in a column and gives the evaluated result. Resultant datatype for Evaluate function in method 2 can changed to evaluate boolean expression and to get boolean results.
System.Console.WriteLine(Evaluate("2 * 4"));
{
return (double)new System.Xml.XPath.XPathDocument
(new System.IO.StringReader("<r/>")).CreateNavigator().Evaluate
(string.Format("number({0})", new
System.Text.RegularExpressions.Regex(@"([\+\-\*])").Replace(expression, " ${1} ")
.Replace("/", " div ").Replace("%", " mod ")));
}
In Method 1 System.Text.RegularExpressions.Regex helps in giving space between operator and also to replace "/" operator to div and "%" operator to mod. XPathNavigator.Evaluate method evaluates the string representing an XPath expression and returns the typed result.
Method 2 :
public static double Evaluate(string expression)
{
System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("expression", string.Empty.GetType(), expression);
System.Data.DataRow row = table.NewRow();
table.Rows.Add(row);
return double.Parse((string)row["expression"]);
}
In Method 2 DataColumn.Expression in System.Data.DataTable is used to create a default row with required expression. Thereby DataTable calculate the values in a column and gives the evaluated result. Resultant datatype for Evaluate function in method 2 can changed to evaluate boolean expression and to get boolean results.
System.Console.WriteLine(Evaluate("2 * 4"));