sneha nagaruru sneha nagaruru - 9 months ago 42
C# Question

How to replace values in 2-D string array

How to perform this task?

int Amount, x=1000,y=200;
string BasedOn="x*12%+y*5%";
//In place of x and y in BasedOn I want to replace with x,y values like (1000*12%+200*5%)
//and the calculated result(130) should be assigned to Amount variable

For now, I split the BasedOn string

string[][] strings = BasedOn
.Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries)
.Select(w => w.Split('*').ToArray())

What to do next? Please help me.

Answer Source

If you want to replace the string AND calculate the result, you can do:

int Amount, x=1000,y=200;
string BasedOn=$"{x}*12/100+{y}*5/100";

DataTable dt = new DataTable();
var v = dt.Compute(BasedOn,"");

v will be your result (130).

EDIT: You have to replace your %'s with division by 100, as the datatable thinks its a mod operator.