How to use a condition with a string inside a condition using C #

Values ​​come from xml , the user only announces what condition to do.

 string condition ="25<10"; 

Now, I want to use this under the following conditions:

 if(condition) { //my condition } 

and i get this error

 Cannot implicitly convert type string to bool 

Can someone tell me how to do this?

+5
source share
3 answers

If the conditions are not so complicated, you can try the old trick with a DataTable :

https://msdn.microsoft.com/en-us/library/system.data.datatable.compute(v=vs.110).aspx

 private static bool ComputeCondition(string value) { using (DataTable dt = new DataTable()) { return (bool)(dt.Compute(value, null)); } } ... string condition ="25<10"; if (ComputeCondition(condition)) { //my condition } 
+4
source

First of all: If you do this, the condition string condition ="25<10" will be 25 <10, not true or flase! If 25, 10 and <from your xml paste them into 3 different lines, such as x, y and z, and compare them like:

 string input = "25<10"; //input form your xml int operatorPosition; //get the position of the operator if(input.contains("<")){ operatorPosition = input.IndexOf("<"); }else{ operatorPosition = input.IndexOf(">"); } //maybe i messed up some -1 or +1 here but this should work this string x = input.Substring(0,operatorPosition-1); string y = input.Substring(operatorPosition+1, input.length-1); string z = input.charAt(operatorPosition); //check if it is < or > if(z.equals("<"){ //compare x and y with < if(Int32.parse(x) < Int32.parse(y)){ //do something }else{ //do something } } //z does not equal < so it have to be > (if you dont have something like = otherwise you need to check this too) else{ if(Int32.parse(x) < Int32.parse(y)){ //do something }else{ //do something } 

There may be a better way to convert a clean string input to an if clause, but I would do it.

0
source

You can use this code for this:

 string statment = "10<25"; // Sample statement string leftOperand = statment.Split('<').First(); string rightOperand = statment.Split('<').Last(); int relationValue = Math.Sign(leftOperand.CompareTo(rightOperand)); if(relationValue == -1) { // leftOperand < rightOperand } else if (relationValue == 0) { // leftOperand == rightOperand } else if (relationValue == 1) { // leftOperand > rightOperand } 

If you just want to check leftOperand < rightOperand , you can use the ternary operator as follows:

 bool condition = Math.Sign(leftOperand.CompareTo(rightOperand)) == -1 ? true : false; 
0
source

Source: https://habr.com/ru/post/1271715/


All Articles