Express conditions to modify an object
$ dotnet add package Viya.RuleEngineWith RuleEngine you can write rules, which consist of an expression and a patch definition, to modify a object/model.
These rules can be defined in yaml or with typed C# objects.
Please see the changelog!
Provided the following input object
Name: Henk
Age: 15
Phone: 0612345678
Address:
StreetName: Hoofdstraat
StreetNumber: 25a
City: Amsterdam
PostalCode: 1234AA
WorkAddress: null # Same type/fields as Address
rules:
- condition: Age < 16
patch:
Age: 25
The condition Age < 16 evaluates to: true
Thus the Age property becomes: 25
rules:
- condition: Phone.StartsWith("06")
patch:
Phone: 0612341234
Address:
City: Hilversum
The condition Phone.StartsWith("06") evaluates to: true
Thus the Phone property becomes 0621341234 and Address.City becomes Hilversum
With a Lambda expression it is possible to use logic to assign the object, take a look at the following examples.
patch:
myProperty1: input => input.Name # referencing the input object
myProperty2: x => $"prefix-{x.Name}-postfix" # using a custom identifier with string interpolation
myYear: _ => DateTime.Now.Year # omitting the input object and using DateTime C# class
rules:
- condition: true
patch: # copy to child object (not null)
WorkAddress: input => input.Address
Here the condition is true
The result becomes:
Name: Henk
Age: 15
Phone: 0612345678
Address:
StreetName: Hoofdstraat
StreetNumber: 25a
City: Amsterdam
PostalCode: 1234AA
WorkAddress:
StreetName: Hoofdstraat
StreetNumber: 25a
City: Amsterdam
PostalCode: 1234AA
Running a benchmark
dotnet run -c Release --project RuleEngine.Benchmark
Results:
All this was not possible without the following libraries: