1

I have a textarea where user can create a dynamic formulas using dropdown lists(for operators, variables etc) like this:

basic / workingDays * attendingDays

where values of basic, workingDays, attendingDays are saved in database. I want to map these variable from database during runtime. How can I do this.

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
John
  • 704
  • 3
  • 12
  • 29
  • check this out http://social.msdn.microsoft.com/Forums/eu/csharplanguage/thread/f92d53b5-1bba-424a-8991-7e9e54787c23 – Waqas Sep 21 '11 at 07:09

2 Answers2

3

NCalc is a very powerful framework that you could try. They let you define dynamic parameters which sounds like exactly what you need. You can do something like this:

var e = new Expression("basic / workingDays * attendingDays);

//Set up a custom delegate so NCalc will ask you for a parameter's value
//   when it first comes across a variable
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
   if (name == "basic")
       args.Result = GetBasicValueFromSomeWhere();
   else if (/* etc. */)
   {
       //....
   }

   //Or if the names match up you might be able to something like:
   args.Result = dataRow[name];
};

var result =  e.Evaluate();

There are also some related questions out there such as this one and this one that give some other options.

Community
  • 1
  • 1
Stephen McDaniel
  • 2,938
  • 2
  • 24
  • 53
  • 1
    This does exact what I needed but I can not use If and else block using NCalc.e.g. if(workingdays > 15) (basic+1000) / workingDays * attendingDays – John Sep 21 '11 at 09:08
  • 1
    NCalc does have a built-in if function. The syntax is slightly different than it might be in C#. You do something like: `if(someCondition, value when true, value when false)` – Stephen McDaniel Sep 21 '11 at 15:23
  • I am trying to do same but it is throwing exception (missing EOF at ',' at line 1:10) Given condition is: var e = new Expression("if(10>11), 10, 12"); – John Sep 22 '11 at 05:29
  • 1
    You have your parenthesis in the wrong place. It should be `new Expression("if(10>11, 10, 12)");`. In NCalc, `if` is a normal function that takes three parameters so you need to have the all three parts inside the parenthesis. – Stephen McDaniel Sep 22 '11 at 07:16
1

Also you can try to exploit Expression property of DataColumn in a DataTable.

Dmitry
  • 3,069
  • 1
  • 17
  • 26