Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert string to if condition

Tags:

c#

.net

Is it possible to convert string

"value > 5 && value <= 10" 

to if statement?

if (value > 5 && value <= 10)
{
   //do something
}

I have conditions stored as strings in DB, so it must be a dynamic conversion

like image 267
Kacper Stachowski Avatar asked Jul 04 '19 13:07

Kacper Stachowski


People also ask

What do you mean by C?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Which language in C?

C is an imperative, procedural language in the ALGOL tradition. It has a static type system. In C, all executable code is contained within subroutines (also called "functions", though not in the sense of functional programming).


2 Answers

Instead you can treat it as a javascript line and can get this done using Windows Script Engines, provided value is a real value instead of variable name.

 if(ScriptEngine.Eval("jscript", "value > 5 && value <= 10"))
   {
     //Your logic
   }

Or if its a variable then you can build a JS function like below to accomplish this:

using (ScriptEngine engine = new ScriptEngine("jscript"))
{
  string JSfunction =  "MyFunc(value){return " + "value > 5 && value <= 10" + "}";

  ParsedScript parsed = engine.Parse(JSfunction);
  if(parsed.CallMethod("MyFunc", 3))
  {  
   // Your Logic
  }
}
like image 181
HarryPotter Avatar answered Sep 21 '22 23:09

HarryPotter


You could use Linq.Expression to build up the expression tree, the one you provided:

"value > 5 && value <= 10"

var val = Expression.Parameter(typeof(int), "x");
var body = Expression.And(
     Expression.MakeBinary(ExpressionType.GreaterThan, val, Expression.Constant(5)), 
     Expression.MakeBinary(ExpressionType.LessThanOrEqual, val, Expression.Constant(10)));

var lambda = Expression.Lambda<Func<int, bool>>(exp, val);
bool b = lambda.Compile().Invoke(6); //true
bool b = lambda.Compile().Invoke(11); //false

This is just an example to get some idea, still you need a smart way to parse and build the tree.

like image 27
Johnny Avatar answered Sep 22 '22 23:09

Johnny