2

I'm working on a project where I need to evaluate some formulas in VB.NET. I've been using the MS Script Control to evaluate some of the simple logical/mathematical formulas.

However, I'm now faced with dealing with string expressions that set variables in my program to certain values. So, for example, let's say I've got the following:

Dim netPrice As Decimal
Dim expressionFormula As String = "netPrice = 0"

I need to be able to evaluate "expressionFormula" and set the netPrice variable to 0. I've been trying different combinations of the .AddObject method in the MS Script Control, but nothing's worked yet.

I should mention this example is only for illustration purposes, the real scenario involves several DataTable objects from a typed DataSet. In the end, some of the fields in my DataTable may need to be set to specific constant values based on these dynamic expressions.

Thanks for the help!

Overhed
  • 1,289
  • 1
  • 13
  • 41

3 Answers3

3

For this kind of functionality, you will need to write your own parser and evaluator.

Take a look at the Linq Expression class - it may help.

Alternatively, depending on your approach, you may be able to write and compile dynamic classes using the CSharpCodeProvider to compile your expressions as C# classes/assemblies.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Thanks for your answer. I ended up taking a more strict approach to the way the formulas can be written (allowing me to parse them) and taking advantage of DataSet/DataTable syntax to "plug in" field and tables names dynamically when setting values. – Overhed Dec 08 '10 at 21:09
2

If you have to handle complex expressions, maybe this library can be helpful : http://flee.codeplex.com/ ?

AFract
  • 8,868
  • 6
  • 48
  • 70
  • Thanks for the link, it doesn't do what I needed, but it looks like it might be a nice replacement to the antiquated MS Script Control that I'm currently using. – Overhed Dec 08 '10 at 21:10
0

Dynamic Linq is what you're looking for

Ali Tarhini
  • 5,278
  • 6
  • 41
  • 66
  • I'm worked a bit with D-Linq, but I don't see how it would help me in doing what I illustrated in my example. – Overhed Dec 08 '10 at 21:11