Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
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 4 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 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!