C# Can a comparison in a String value return a Boolean value. eg. “5 < 10” return true

后端 未结 6 1741
故里飘歌
故里飘歌 2020-12-22 14:11

Is there a way a comparison in a string value can return a Boolean value. Example. If (5 > 5000) would obviously return a false value. But what i wanted to do i

相关标签:
6条回答
  • 2020-12-22 14:18

    No built-in way but NCalc can help here

    NCalc.Expression expr = new NCalc.Expression("5>10");
    bool b = (bool)expr.Evaluate();
    

    You can even use parameters

    NCalc.Expression expr = new NCalc.Expression("a<b");
    
    expr.EvaluateParameter += (name, args) =>
      {
          if (name == "a") args.Result = 5;
          if (name == "b") args.Result = 10;
      };
    bool b = (bool)expr.Evaluate();
    
    0 讨论(0)
  • 2020-12-22 14:29

    Short answer: no.

    Long answer: feel free to parse the string yourself, looking for > < and =. Split by whitespace, parse ints then evaluate. It might get harder if you want it to work with parentheses as well...

    0 讨论(0)
  • 2020-12-22 14:34

    There is no built-in way to do this.

    Although there are a couple of ways to approach this, one is to simply parse the text yourself. I did this in the code presented in the article A C# Expression Evaluator. You might want to review that code.

    0 讨论(0)
  • 2020-12-22 14:35

    Not directly, per se (short of the unsafe Javascript eval-execute-my-data hack) but you can try parsing it yourself, depending on how complicated of an expression you want to accept. For example, this should work with the string you have:

    var arr = com.Split('>').Select(x=>int.Parse(x.Trim())).ToArray();
    return arr[0] > arr[1];
    

    You can also use regular expressions to get more complicated (untested, but it ought to work):

    var r = new Regex(@"(\d+)\b*(<|>|=|<=|>=)\b*(\d+)")
    var match = r.Match(com);
    if(match.Success)
    {
        var a = int.Parse(match.Captures[0]);
        var b = int.Parse(match.Captures[2]);
    
        switch(match.Captures[1])
        {
             case "<":
                 return a < b;
             case "=":
                 return a = b;
             case ">":
                 return a > b;
             case "<=":
                 return a <= b;
             case "<=":
                 return a >= b;
        }
    }
    
    //uh-oh
    throw new ArgumentException("com");
    
    0 讨论(0)
  • 2020-12-22 14:38

    No, this can't be done directly. You should write your own class or extend the String class. For handling a string such as "5 < 10", you need your own method.

    You should search the string for signs that indicate comparison, such as "<", "==" etc, then split it and perform the comparison.

    Basically: doing it yourself is the only way, but you can try to do it in an elegant way.

    0 讨论(0)
  • 2020-12-22 14:42

    Consider using FLEE:

    Flee is an expression parser and evaluator for the .NET framework. It allows you to compute the value of string expressions such as sqrt(a^2 + b^2) at runtime. It uses a custom compiler, strongly-typed expression language, and lightweight codegen to compile expressions directly to IL. This means that expression evaluation is extremely fast and efficient. Try out the demo, which lets you generate images based on expressions, and see for yourself.

    With FLEE you can easily accomplish this using something like:

            var con = new ExpressionContext();
            const string com = @"5 > 5000";
            var comparison = con.CompileDynamic(com);
            var result = comparison.Evaluate();
            MessageBox.Show(result.ToString());
    

    HTH...

    0 讨论(0)
提交回复
热议问题