Tengo una cadena que contiene expresiones de condición:
"weight=65,age>18"
Quiero comprobar si la condición es verdadera.
Por ejemplo:
int weight = 70; int age= 19; string conditions = "weight=65,age>18";
En el ejemplo anterior, la condición de weight
es false
y la condición age
es true
. Por lo tanto, el resultado debería ser false
.
Quiero verificar la condición y regresar si se cumple la condición.
Está buscando un analizador , como una posible solución rápida, puede probar 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))); }
Luego
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));