public object GetArithmeticValue(string expression) { //实例化DataTable DataTable dt = new DataTable(); //进行运算 var result = dt.Compute(expression,""); return result; }
调用:
结果:
使用SQL语句中Select语句实现
引入System.Data.SqlClient空间命名(此处以SqlServer为例)
1 2 3 4 5 6 7 8 9 10 11 12 13
public object GetArithmeticValue(string expression) { //拼接Sql语句 string SQL = "SELECT "+expression+" AS RESULT_VALUE"; //构建sqlserver连接实例 SqlConnection conn = new SqlConnection("sql连接语句"); //构建sql指令实例 SqlCommand cmd = new SqlCommand(SQL, conn); //执行sql语句 object obj = cmd.ExecuteScalar(); //执行SQL. //返回数据结果 return obj; }
为简化结果,此处仅仅是显示拼接的Sql语句
1
SELECT (3+4)/12*1.0 AS RESULT_VALUE
数据库执行结果:
通过CalcParenthesesExpression函数( 后序式计算 )
引入GrapeCity.CalcEngine.Expressions程序集
1 2 3 4 5 6
public object GetArithmeticValue(string expression) { string result = new CalcParenthesesExpression() .CalculateParenthesesExpression(expression); return result; }
public object GetArithmeticValue(string expression) { //创建引擎的实例 CalcEnginer calcEngine = new CalcEnginer(); //执行表达式函数 var result = calcEngine.Evaluate(expression); return result; }
public object GetArithmeticValue(string expression) { //构造实例 Expression method = new Expression(expression); //执行函数获取计算结果 var result = method.Evaluate(); return result; }