How to compute expression - c#

Consider this code fragment;
int sum = 0;
sum = Expression.Evaluate("1+1");
where the value of sum = 2
I do have an expression that will compute values but i want that expression to be build programatically then evaluate the result. I don't have any idea what class or namespace that I will dealing with. Anyone can help me.

You could use Expression Trees:
Expression trees represent code in a tree-like data structure, where
each node is an expression, for example, a method call or a binary
operation such as x < y.
You can compile and run code represented by expression trees.
Expression Trees (C# and Visual Basic)
Expression Tree Basics
Note: This problem can be solved using System.Reflection.Emit and work directly with MSIL, but the resulting code is hard to write and read.
After a little browsing, I suggest you checkout Flee on Codeplex: Fast Lightweight Expression Evaluator :
Flee is an expression parser and evaluator for the .NET framework. It
allows you to compute the value of string expressions such as sqrt(a^2
+ b^2) at runtime. It uses a custom compiler, strongly-typed expression language, and lightweight codegen to compile expressions
directly to IL. This means that expression evaluation is extremely
fast and efficient.

You can build Expressions trees either using lambdas or by building them programatically using classes in the System.Linq.Expressions namespace.
See MSDN for more info.

Have you seen http://ncalc.codeplex.com ?
It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:
Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");
e.Parameters["Pi2"] = new Expression("Pi * Pi");
e.Parameters["X"] = 10;
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (name == "Pi")
args.Result = 3.14;
};
Debug.Assert(117.07 == e.Evaluate());
It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.
It also supports logical operators, date/time's strings and if statements.

Related

Expression method for NULLIF (with Divide)

I am using C# 4.5.2. I Have to call a SumDenominator method as a denominator for an Expression.Divide method:
var SumDenominatorExpression = Expression.Call(
null,
SumDenominatorMethod,
Parameter,
SumDenominatorSelector
);
then later on the actual Expression.Divide reads:
var FractionExpression = Expression.Divide(
SumNumeratorExpression,
SumDenominatorExpression
);
if the denominator's selector generates zero then the divide by zero exception is thrown. I tried to solve this by converting the Sum expression into a Nullable<> but the Divide method doesn't swallow null values. And the SQLServer (my provider) doesn't have a NULLIF function (i.e. System.Data.Entity.SqlServer.SqlFunctions) that I can wrap a Call expression around.
How to people tackle zeros in the denominator with C# Expression trees?
UPDATE
Here are the expression methods I ended up using:
Expression.Condition(
Expression.Equal(
SumDenominatorExpression,
Expression.Constant(0.0, typeof(double))
),
Expression.Constant(0.0, typeof(double)),
FractionExpression
)
It sounds like you want EF to be able to translate this expression. That restricts the kinds of patterns we can use. The following should work:
FractionExpression =
(SumDenominatorExpression == 0)
? (int?)null /*default value - pick what you want*/
: (SumNumeratorExpression / SumDenominatorExpression);
(I'm writing the expression tree as C# for typing speed.)
Since EF does not support trees that have variables you will need to use the SumDenominatorExpression expression twice. Hopefully SQL Server will optimize that and evaluate it only once.

Very simple explanation of a Lambda Expression

I am looking for a very simple - basic - no hardcore programming mumbo jumbo, simply put a generalized overview of a Lambda Expression in layman's terms.
A lambda expression is, simply put, a re-useable expression which takes a number of arguments:
x => x + 1;
The above expression reads "for a given x, return x + 1".
In .NET, this is powerful, because it can be compiled into an anonymous delegate, a nameless function you can declare inline with your code and evaluate to get a value:
int number = 100;
Func<int, int> increment = x => x + 1;
number = increment(number); // Calls the delegate expression above.
However, the real power of a lambda expression is that it can be used to initialize an in-memory representation of the expression itself.
Expression<Func<int, int>> incrementExpression = x => x + 1;
This means that you can give that expression to something like LINQ to SQL and it can understand what the expression means, translating it into a SQL statement that has the same meaning. This is where lambdas are very different from normal methods and delegates, and normally where the confusion begins.
Lambda Expressions are inline functions that have a different syntax to regular functions.
Example Lambda Expression for squaring a number.
x => x * x
A small unnamed inline method. Is that basic enough for you? I'm not sure what you are looking for exactly.
You also said in "layman's" terms - I presume that you have some level of software development experience (so not a complete layman)
In non functional programming languages expressions (that act on variables) perform calculations and they perform those calculations once.
Lambda expressions allow you to define (in an expression) via different syntax code that can work on a list and can conceptually be considered a function.
You could simplify this to say "They let you define functions in expressions".
Does not quite get to the "why". The why is the more interesting, in my opinion. Lambda expression allow for the manipulation of functions and partial functions.

How to get a calculated value from a compiled LambdaExpression?

I'm currently working on a project at work, and we are using the Telerik RadControls for Silverlight. In their Q1 2011 release, they added a new control called the Rad Expression Editor. In the Rad Expression Editor, you can pass in an object and create formulas (or expressions), and the editor window will give you a preview of the result of the expression. I've spoken with Telerik about this and they intentionally did not expose the result of this, but mentioned that I could use LambdaExpression.Compile(). I'm very new to Linq and using Lambda Expressions in general, but started looking into this.
As an example, lets say I have an object called Finances, and in that object, there are 4 nullable decimal fields (values): Debit (10), DebitYTD (100), Credit (20) and CreditYTD (200). In the formula, I want to do something like: Debit - Credit + DebitYTD - CreditYTD.
The Telerik Rad Expression Editor will give me the expression that is generated:
ExpressionEditor.Expression = {Param_0 => ((Param_0.Debit - Param_0.Credit + Param_0.DebitYTD - Param_0.CreditYTD}
The result of this expression should be -110. I need to be able to get the value that is calculate in the expression, but have not been able to figure out how to get this number. Can anyone please explain how this can be accomplished? Thanks.
You haven't really told us much about the API which it exposes, but it sounds like you could use:
var compiled = ExpressionEditor.Expression.Compile();
var result = compiled(input);
where input is an appropriate variable of type Finances.
EDIT: Okay, as the expression isn't exposed nicely:
var typeSafe = (Expression<Func<Finance, decimal?>>) ExpressionEditor.Expression;
var compiled = typeSafe.Compile();
var result = compiled(input);
I had very similar requirements. There was a need to compile expression and evaluate at runtime against different instances. However function compilation is not so trivial as you have to know the type of the result value during compile time and in most of the cases this will be impossible: user writes "1+1" and you get System.Int32, or user writes "(1+1).ToString()" and you get System.String. I'm sure this is the point where you experience (or will experience) difficulties.
In order to solve the expression compilation problem I would recommend jumping into DLR (Dynamic Language Runtime). You will need to reference "Microsoft.CSharp" assembly for your Silverlight project. As you need just access to "Compile" method for the expression (that is already in there), it will be fair enough doing that against "dynamic" object. Here's a short sample to demonstrate that:
dynamic dynamicExpression = expressionEditor.Expression;
dynamic compiledExpression = dynamicExpression.Compile();
object executionResult = compiledExpression(myInstance);
The "executionResult" variable will hold the result of expression evaluation. Now you can do whatever you need to do with the result.
Hope that helps

evaluate an arithmetic expression stored in a string (C#)

I'm working on a application in C# in which I want to calculate an arithmetic expression that is given as a string.
So like I got a string:
string myExpr="4*(80+(5/2))+2";
And I want to calculate the outcome of the arithmetic expression.
While in a language such as Javascript, PHP etc. you could just use Eval to do the trick this doesnt seem to be an option in C#.
I suppose it is possible to write a code to devide it into countless simple expressions, calculate them and add them together but this would take quite some time and I'm likely to have lots of troubles in my attempt to do so.
So... my question, Is there any 'simple' way to do this?
There's a javascript library you can reference, then just do something like:
var engine = VsaEngine.CreateEngine();
Eval.JScriptEvaluate(mySum, engine);
Edit;
Library is Microsoft.JScript
You could just call the JScript.NET eval function. Any .NET language can call into any other.
Have you seen http://ncalc.codeplex.com ?
It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:
Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");
e.Parameters["Pi2"] = new Expression("Pi * Pi");
e.Parameters["X"] = 10;
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (name == "Pi")
args.Result = 3.14;
};
Debug.Assert(117.07 == e.Evaluate());
It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.
It also supports logical operators, date/time's strings and if statements.
I've used NCalc with great success. It's extremely flexible and allows for variables in your formulas. The formula you listed in your question could be evaluated this easily:
string myExpr = "4*(80+(5/2))+2";
decimal result = Convert.ToDecimal(new Expression(myExpr).Evaluate());
You need to implement an expression evaluator. It's fairly straightforward if you have the background, but it's not "simple". Eval in interpreted environments actually re-runs the language parser over the string; you need to emulate that operation, for the bits you care about, in your C# code.
Search for "expression evaluators" and "recursive descent parser" to get started.
If you have Bjarne Stroustrup's The C++ Programming Language, in Chapter 6 he explains step by step (in C++) how to do exactly what Chris Tavares suggests.
It's straightforward but a little heady if you're not familiar with the procedure.
I needed to do something similar for an undergrad projectand I found this
Reverse Polish Notation In C#
Tutorial and code to be extremely valuable.
It's pretty much just an implementation of converting the string to Reverse Polish Notation then evaluating it. It's extremely easy to use, understand and add new functions.
Source code is included.
Try something like this:
int mySum = 4*(80+(5/2))+2;
var myStringSum = mySum.toString();

Parser for query filter expression tree

I am looking for a parser that can operate on a query filter. However, I'm not quite sure of the terminology so it's proving hard work. I hope that someone can help me. I've read about 'Recursive descent parsers' but I wonder if these are for full-blown language parsers rather than the logical expression evaluation that I'm looking for.
Ideally, I am looking for .NET code (C#) but also a similar parser that works in T-SQL.
What I want is for something to parse e.g.:
((a=b)|(e=1))&(c<=d)
Ideally, the operators can be definable (e.g. '<' vs 'lt', '=' vs '==' vs 'eq', etc) and we can specify function-type labels (e.g. (left(x,1)='e')). The parser loads this, obeys order precedence (and ideally handles the lack of any brackets) and then calls-back to my code with expressions to evaluate to a boolean result - e.g. 'a=b'?). I wouldn't expect the parser to understand the custom functions in the expression (though some basic ones would be useful, like string splitting). Splitting the expression (into left- and right-hand parts) would be nice.
It is preferable that the parser asks the minimum number of questions to have to work out the final result - e.g. if one side of an AND is false, there is no point evaluating the other side, and to evaluate the easiest side first (i.e. in the above expression, 'c<=d' should be assumed to be quicker and thus evaluated first.
I can imagine that this is a lot of work to do, however, fairly common. Can anyone give me any pointers? If there aren't parsers that are as flexible as above, are there any basic parsers that I can use as a start?
Many Thanks
Lee
Take a look at this. ANTLR is a good parser generator and the linked-to article has working code which you may be able to adapt to your needs.
You could check out Irony. With it you define your grammar in C# code using a syntax which is not to far from bnf. They even have a simple example on their site (expression evaluator) which seems to be quite close to what you want to achieve.
Edit: There's been a talk about Irony at this year's Lang.Net symposium.
Hope this helps!
Try Vici.Parser: download it here (free) , it's the most flexible expression parser/evaluator I've found so far.
If it's possible for you, use .Net 3.5 expressions.
Compiler parses your expression for you and gives you expression tree that you can analyze and use as you need. Not very simple but doable (actually all implementations of IQueryable interface do exactly this).
You can use .NET expression trees for this. And the example is actually pretty simple.
Expression<Func<int, int, int, int, bool>> test = (int a, int b, int c, int d) => ((a == b) | (c == 1)) & (c <= d);
And then just look at "test" in the debugger. Everything is already parsed for you, you can just use it.
The only problem is that in .NET 3.5 you can have only up to 4 arguments in Func. So, I changed "e" to "c" in one place. In 4.0 this limit is changed to 16.

Categories