jsandv
jsandv

Reputation: 306

C# evaluate a string expression and return the result

Trying to figure out which approach to use in .net/C# to evaluate a simple expression in runtime. Code must be .net standard compliant, and I dont want weird dependecies.

I have looked into using using Microsoft.CodeAnalysis.CSharp.Scripting: How can I evaluate C# code dynamically? but it seems overkill for my use case.

public class Evaluate
    {
        private Dictionary<string, object> _exampleVariables = new Dictionary<string, object>
        {
            {"x", 45},
            {"y", 0},
            {"z", true}
        };
        private string _exampleExpression = "x>y || z";
        private string _exampleExpression2 = @"if(x>y || z) return 10;else return 20;
";
        public object Calculate(Dictionary<string, object> variables, string expression)
        {
            var result = //Magical code
            return result;
        }
    }

Upvotes: 2

Views: 4559

Answers (2)

Binh
Binh

Reputation: 291

You can try my Matheval library. It can evaluate string expression in pure C# and support IFELSE, SWITCH statement. I don't use any dependencies.

using System;
using org.matheval;
                    
public class Program
{
    public static void Main()
    {
        Expression expression = new Expression("IF(time>8, (HOUR_SALARY*8) + (HOUR_SALARY*1.25*(time-8)), HOUR_SALARY*time)");
        //bind variable
        expression.Bind("HOUR_SALARY", 10);
        expression.Bind("time", 9);
        //eval
        Decimal salary = expression.Eval<Decimal>();    
        Console.WriteLine(salary);
    }
}

View my repo at: https://github.com/matheval/expression-evaluator-c-sharp/

Upvotes: 4

Marco Salerno
Marco Salerno

Reputation: 5203

In C# you can do this:

class Program
{
    private static Func<Dictionary<string, object>, object> function1 = x =>
    {
        return ((int)x["x"] > (int)x["y"]) || (bool)x["z"];
    };

    private static Func<Dictionary<string, object>, object> function2 = x =>
    {
        if (((int)x["x"] > (int)x["y"]) || (bool)x["z"])
        {
            return 10;
        }
        else
        {
            return 20;
        }
    };

    static void Main(string[] args)
    {
        Dictionary<string, object> exampleVariables = new Dictionary<string, object>
        {
            {"x", 45},
            {"y", 0},
            {"z", true}
        };

        Console.WriteLine(Calculate(exampleVariables, function2));
    }

    public static object Calculate(Dictionary<string, object> variables, Func<Dictionary<string, object>, object> function)
    {
        return function(variables);
    }
}

Upvotes: 0

Related Questions