As per title, is it possible to parse and evaluate inequalities obtaining a true/false result?
As example:
Expression e = Infix.ParseOrThrow("A<B");
It throws:
My current approach:
public static bool CheckInequalitySatisfaction(string inequality, BoxDimensionValues values = null)
{
try
{
if (string.IsNullOrWhiteSpace(inequality))
throw new ArgumentNullException(nameof(inequality));
if (inequality.ToLower().Equals("false"))
return false;
if (inequality.ToLower().Equals("true"))
return true;
var matches = Regex.Match(inequality, "(?<left>.+)(?<operand>==|<=|>=|<|>)(?<right>.+)");
if (!matches.Success)
throw new ArgumentException($"The inequality is not valid {inequality}", nameof(inequality));
var leftExpression = matches.Groups["left"].Value;
if (!TryEvaluateExpression(leftExpression, values, out int leftValue))
throw new ArgumentException($"The left expression of the inequality is not valid {leftExpression}", nameof(inequality));
var rightExpression = matches.Groups["right"].Value;
if (!TryEvaluateExpression(rightExpression, values, out int rightValue))
throw new ArgumentException($"The right expression of the inequality is not valid {rightExpression}", nameof(inequality));
var inequalityOperator = matches.Groups["operand"].Value;
return inequalityOperator switch
{
"==" => leftValue == rightValue,
"<=" => leftValue <= rightValue,
">=" => leftValue >= rightValue,
"<" => leftValue < rightValue,
">" => leftValue > rightValue,
_ => throw new NotImplementedException($"The operator {inequalityOperator} is not supported for inequalities evaluation"),
};
}
catch (Exception ex)
{
ex.Log(MethodBase.GetCurrentMethod());
throw;
}
}