-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;
}
4
  • 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. Commented Jun 25, 2015 at 16:09
  • That was there by mistake, sorry, would it be possible to have an array of operators then ? Commented Jun 25, 2015 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. Commented Jun 25, 2015 at 16:11
  • possible duplicate of Convert string value to operator in C# Commented Jun 25, 2015 at 16:12

3 Answers 3

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.
Sign up to request clarification or add additional context in comments.

3 Comments

Ohh...that's a very elegant solution :)
That was the kind of thing I was looking for, Thank you.
@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.
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.

1 Comment

This should be a comment.
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.