Im trying to figure out a way to build a conditional dynamically.
In example
var greaterThan = ">";
var a = 1;
var b = 2;
if(a Convert.ToOperator(greaterThan) b) {...}
I did read this post but could not quite understand how to implement some of the stuff. C# convert a string for use in a logical condition
Ano advice is highly appreciated
Thanks
To turn string into operator with Python, we can use the operator module. to create the ops dict that has the operator strings as keys and the operators as the values. Then we can get the operator by the string key and use them with operands.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
I wasn't going to post it, but thought that it might be of some help. Assuming of course that you don't need the advanced generic logic in Jon's post.
public static class Extension
{
public static Boolean Operator(this string logic, int x, int y)
{
switch (logic)
{
case ">": return x > y;
case "<": return x < y;
case "==": return x == y;
default: throw new Exception("invalid logic");
}
}
}
You could use the code like this, with greaterThan
being a string
with the wanted logic/operator.
if (greaterThan.Operator(a, b))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With