-3

I am trying to use an operator which is selected from an array in an if statement. As the code is below I cannot compile it. Is there anyway around this ?

string[] operators = new string[]{"<",">","=","!="};

decimal value = Convert.ToDecimal(values[j]);
var operator1 = (operators[Convert.ToInt32(IQueryTypeList[k])]);
int jjj = Convert.ToInt32(NTestValueList[k]);

if (value operator1 jjj)
{
    IsActive = true;
}
else
{
    IsActive = false;
}
JackWhiteIII
  • 1,388
  • 2
  • 11
  • 25
jOE127
  • 123
  • 1
  • 6
  • I'm not sure what `@value` is, but you can't use a string as the comparison operator in an `if` statement - you have to use the actual operator. – Tim Jun 25 '15 at 16:09
  • That was there by mistake, sorry, would it be possible to have an array of operators then ? – jOE127 Jun 25 '15 at 16:10
  • You can still use an array of operators, but you'll need to write logic using `if/else` or `switch` to determine what the operator is, and then in that block write the *proper* code. – Tim Jun 25 '15 at 16:11
  • possible duplicate of [Convert string value to operator in C#](http://stackoverflow.com/questions/7086058/convert-string-value-to-operator-in-c-sharp) – DavidG Jun 25 '15 at 16:12

3 Answers3

2

One way is to perform a string comparison with either an if-else chain or a switch statement. I don't know the exact syntax C#, so consider the following as pseudocode:

if (operator1.equals("<"))
    IsActive = value < jjj
// etc.
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • Ohh...that's a very elegant solution :) – Tim Jun 25 '15 at 16:12
  • That was the kind of thing I was looking for, Thank you. – jOE127 Jun 25 '15 at 16:14
  • @Tim Yah, I'm sure there are other, more elegant solutions. I'm a C# noob coming from Java. Of course, if this were part of a parser of some kind, I'd also build "node" classes which represent the operators in an abstract syntax tree. This would allow polymorphism rather than explicit `if` or `switch`. – Code-Apprentice Jun 25 '15 at 16:16
0

You can not simply use the string as an operator but you could write an extension method for using strings. Have a look here for more in-depth explanations.

Community
  • 1
  • 1
dhh
  • 4,289
  • 8
  • 42
  • 59
0

You can use the switch-case logic:

string[] operators = new string[]{"<",">","=","!="};
decimal value = Convert.ToDecimal(values[j]);
var operator1 = (operators[Convert.ToInt32(IQueryTypeList[k])]);
int jjj = Convert.ToInt32(NTestValueList[k]);

switch (operator1)
{
    case "<":
        //do something here
        break;
    case ">":
         //do something here
        break;
    case "=":
        //do something here
        break;
    case "!=":
        //do something here
        break;
}
laskdjf
  • 1,166
  • 1
  • 11
  • 28