• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

147
Views
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.

over 3 years ago · Santiago Trujillo
1 answers
Answer question

0

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));
over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error