1

String value comes from a cell from database.

For example:

"model.Number == dtoModel.Number"

I want to use this string in a if condition like this;

if(model.Number == dtoModel.Number)
{
  //some logic
}

'model' and 'dtoModel' are objects of some classes.

Can anyone tell me how to do this?

I haved tried Expression type operators but i cant see any result in stackoverflow site.

Good Night Nerd Pride
  • 8,245
  • 4
  • 49
  • 65
akyuzerdi
  • 11
  • 2
  • 6
    I would say this is doable , but What exactly are you trying to achieve ? Provide more details. – AVTUNEY Mar 13 '23 at 09:20
  • Does this answer your question? [Convert string containing bool condition to bool (C#)](https://stackoverflow.com/questions/73769645/convert-string-containing-bool-condition-to-bool-c) – Connor Stoop Mar 13 '23 at 09:36
  • 1
    You could use Roslyn (the C# compiler) programmatically for this: https://www.strathweb.com/2018/01/easy-way-to-create-a-c-lambda-expression-from-a-string-with-roslyn/ – Good Night Nerd Pride Mar 13 '23 at 09:55
  • You could also make your life easier and store the expression in 3 different columns: `LeftOperandPropertyName`, `OperatorSymbol`, `RightOperandPropertyName`. – Good Night Nerd Pride Mar 13 '23 at 10:00
  • The point is though, that this is not as easy as you might expect so you should think carefully if there are easier ways to solve your problem. – Good Night Nerd Pride Mar 13 '23 at 10:04
  • If `model.Number == dtoModel.Number` (or any part of it) is a string, it should be in quotes. – Rufus L Mar 13 '23 at 10:05
  • 2
    Why you need that? It is certainly an [xy-problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What was the real problem that you were trying to solve when you created that column? – Tim Schmelter Mar 13 '23 at 10:10
  • If number is of type string, you can use Equals. Look at https://learn.microsoft.com/en-us/dotnet/csharp/how-to/compare-strings – Ihdina Mar 13 '23 at 10:25

2 Answers2

2

DynamicExpresso is a nice library that allows to execute C# expressions from a strings.

You can do:

using DynamicExpresso;
...

var interpreter = new Interpreter()
    .SetVariable("model", model)
    .SetVariable("dtoModel", dtoModel);

bool result = (bool)interpreter.Eval("model.Number == dtoModel.Number");

This has a performance cost so do your own research to decide if it is suitable for your application.

Dimitris Maragkos
  • 8,932
  • 2
  • 8
  • 26
-1

Try This:

if (string.Equals(model.Number, dtoModel.Number))

or in my case:

var CNF_paperFee11 = new CNF_FeeExamEntryPaper();
var CNF_paperFee22 = new CNF_FeeExamEntryPaper();
if (CNF_paperFee11.EntryKey == CNF_paperFee22.EntryKey)

OR

if (String.Equals(CNF_paperFee11.EntryKey, CNF_paperFee22.EntryKey))
Segel
  • 22
  • 1
  • 5
Maddy
  • 87
  • 5
  • 1
    That's not what the OP was asking: they want to go from a condition specified as string, to a real executable condition – Hans Kesting Mar 13 '23 at 10:29