Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string value to operator in C#

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

like image 513
Eric Herlitz Avatar asked Aug 16 '11 22:08

Eric Herlitz


People also ask

How do you change a string to an operator?

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.

How to change string into int c++?

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.

How do you convert a string to a number in Python?

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") .


1 Answers

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))
like image 70
eandersson Avatar answered Sep 26 '22 01:09

eandersson