how to dynamically generate a formula and solive it by selecting multiple rows using linq
hi guys i have an array called tblCeMaintMatrix.ToArray()) with a result of :
[0]: { xValue = 0, Operator = 43 '+' }
[1]: { xValue = 1, Operator = 43 '+' }
[2]: { xValue = 12, Operator = 45 '-' }
i made a foreach loop to solve this however i encountered some errors. I think i confused the logic for this..
foreach (var a in tblCeMaintMatrix.ToArray())
{
{
value = operate((a.Operator).ToString(),a.xValue.Value );
}
decimal value2 = value;
}
private decimal operate(String a, Decimal value)
{
Decimal Value = 0;
if (a == "+")
{
Value = value + value;
}
if (a == "-")
{
Value= value - value;
}
if (a == "*")
{
Value = value * value;
}
if (a == "/")
{
Value = value / value;
}
return Value;
}
开发者_StackOverflow社区my problem is that
a) what is does is this :
0 + 0 = 0
1 + 1 = 2
12 - 12 = 0
instead of 0 + 1 -12.
b) it doesnt retain the value.
how can i modify this to solve the problem? thanks
Non-tested code, I wish it's correct..
decimal result = 0;
foreach (var a in tblCeMaintMatrix.ToArray())
{
{
result = operate((a.Operator).ToString(),a.xValue.Value,result);
}
}
private decimal operate(String a, Decimal value, Decimal result)
{
switch (a)
{
case "+": result += value; break;
case "-": result -= value; break;
case "*": result *= value; break;
case "/": result /= value; break;
default: result = value; break;
}
return result;
}
EDIT to ignore the first operator, I think you need to set your first operator to empty, like:
[0]: { xValue = 0, Operator = '' }
[1]: { xValue = 1, Operator = 43 '+' }
[2]: { xValue = 12, Operator = 45 '-' }
and see the modified Operate method.
Right now you are only passing a single value to your operate
method, and using it as both operands. You need to also pass the running total of your code to the function:
Decimal total = 0;
foreach (var a in tblCeMaintMatrix.ToArray())
{
{
total = operate((a.Operator).ToString(),total, a.xValue.Value );
}
decimal value2 = value;
}
private decimal operate(String a, Decimal left, Decimal right)
{
Decimal Value = 0;
if (a == "+")
{
Value = left + right;
}
if (a == "-")
{
Value= left - right;
}
if (a == "*")
{
Value = left * right;
}
if (a == "/")
{
Value = left / right;
}
return Value;
}
It's not clear what's your using value2
to represent in your original function.
精彩评论