Search code examples
c#eval

How to check if a set of conditions in a string is true


I have a string that contains condition expressions:

"weight=65,age>18"

I want to check if the condition is true.

For example:

int weight = 70;
int age= 19;
string conditions = "weight=65,age>18";    

In the above example weight condition is false and age condition is true. Hence the result should be false.

I want to check the condition and return if the condition is satisfied.


Solution

  • You are looking for a parser, as a possible quick solution you can try DataTable.Compute one:

    using System.Data;
    
    ...
    
    private static T RunWithVariables<T>(
      string formula, params (string name, object value)[] variables) {
      
      using DataTable table = new();
    
      foreach (var (n, v) in variables)
        table.Columns.Add(n, v is null ? typeof(object) : v.GetType());
    
      table.Rows.Add();
    
      foreach (var (n, v) in variables)
        table.Rows[0][n] = v;
    
      table.Columns.Add("__Result", typeof(double)).Expression = formula 
        ?? throw new ArgumentNullException(nameof(formula)); ;
    
      return (T)(Convert.ChangeType(table.Compute($"Min(__Result)", null), typeof(T)));
    }
    

    Then

    int weight = 70;
    int age = 19;
    
    string conditions = "weight=65,age>18";
    
    var result = RunWithVariables<bool>(conditions.Replace(",", " and "), 
      (nameof(weight), weight), 
      (nameof(age), age));