Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use if condition with string inside the condition using c# [closed]

Tags:

c#

asp.net

The values are comes from xml, user only declare what condition to do.

string condition ="25<10";

Now, I want to use this in if condition like:

if(condition)
{
    //my condition
}

and I am getting this error

Cannot implicitly convert type string to bool

Can anyone tell me how to do this?

like image 697
Vinoth Avatar asked Sep 12 '17 07:09

Vinoth


People also ask

Can we pass string in if condition?

The condition needs to be in string format because in a real world application, the condition will be pulled out of an existing HTML block using a regular expression and is therefore returned in string format.

Can you put multiple conditions in an if statement in C?

Nested if statements mean an if statement inside another if statement. Yes, both C and C++ allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement.


1 Answers

If provided conditions are not that complex, you can try an old trick with DataTable:

https://msdn.microsoft.com/en-us/library/system.data.datatable.compute(v=vs.110).aspx

private static bool ComputeCondition(string value) {
  using (DataTable dt = new DataTable()) {
    return (bool)(dt.Compute(value, null));
  }
}

...

string condition ="25<10"; 

if (ComputeCondition(condition)) {
   //my condition  
}
like image 135
Dmitry Bychenko Avatar answered Oct 17 '22 18:10

Dmitry Bychenko