Home > Back-end >  How to compare dynamically in .NET Core
How to compare dynamically in .NET Core

Time:07-27

This is the conditional rule configured in the database. The rules configured for each user are as follows。

| key  | expression     |rule|
|:---- |:--------------:|---:|
| 001  | >=500 and <=600| 1.2|
| 001  | >600           | 2.0|
| 002  | ==400          | 4.0|
| 002  | !=700          | 5.0|
| 003  | ==100 || ==200 | 0.5|

I need to get the conditional dynamic judgment that the key is 001 Below is my current code, I want generated C# code like this

if (item.TotalDaySam >= 500 && item.TotalDaySam <= 600)
                    {
                        // return Amount * 001 rule(1.2)
                    }
                    else if (item.TotalDaySam > 600)
                    {
                        // return Amount * 001 rule(2.0)
                    }
                    else
                    {
                        // retrun Amount
                    }

How do I get the configuration of the database to dynamically generate the judgment code to perform different logical calculations. I found a similar project RulesEngine, but I don't know how to implement it.

CodePudding user response:

If you can store your data like this :

  • x>=500 && x<=600
  • x>600
  • x==600
  • x!=600

And then iterate foreach line replacing each time x by "item.TotalDaySam".

Finally you can find help from this post to parse the string into a if statement : C# Convert string to if condition

(sorry for the answer instead of comment I am not expert enough to have the right to comment ^^)

  • Related