Evaluating List<String> as a mathematical expression
I have a List<String>
that is full of values and operators.
["123", "+", "(", "890", "-", "15.00", ")"]
I know that I can make an algorithm that will push these numbers and and operators onto a stack and pop them off and evaluate as I go. But, is there a better way to do开发者_运维百科 with without using a external library?
Pushing the numbers and operators onto a stack would be an interpreter.
The obvious better way to do this (for some definition of "better") is to write a compiler!
You already have the input split into lexical tokens, so you can skip implementing a lexer and can dive right into building the AST. You can find suitable classes to transform your input to in the System.Linq.Expressions Namespace; have a look at the Expression Class. You can wrap the result in a lambda expression, compile it to IL and execute it on the CLR!
You can join the List
and then let the compiler evaluate it at runtime as Mehrdad stated.
Expression e = new Expression("5 * 2");
e.Evaluate();
I found a very similar question already asked here
update :
NCalc "NCalc - Mathematical Expressions Evaluator for .NET" even though this is an external library I think it is an open source project which means you can add the code directly to your project.
Update :
You can use the String.Join
function to join the List.
string formula = String.Join("",listMathOperators);
You can always use the C# compiler classes in the .NET framework to evaluate it as a C# expression...
I have a complete class that calculates any expression.
First, you need to extract all strings of your list to a single string, like:
string sExpression = "123+(890-15.00)";
Second, you need to evaluate this expression in a parser, I have a complete class that makes this for you, but I can't attach files here.
精彩评论