CSharp · Console
// C# Eval Expression
// Doc: https://eval-expression.net/eval-execute
// @nuget: Z.Expressions.Eval
/*
### The parameters
You have multiple different ways how you can pass your parameters. Furthermore, there is no best way to pass parameters as everything depends on your scenario and preference:
1. `Eval.Execute<TResult>(string code)`: https://dotnetfiddle.net/4vOu2H
2. `Eval.Execute<TResult>(string code, object parameters)`: https://dotnetfiddle.net/wdLPTE
3. `Eval.Execute<TResult>(string code, params object[] parameters)`: https://dotnetfiddle.net/Q0gWZ3
---
2 - In the case of `Eval.Execute<TResult>(string code, object parameters)`, the object parameters can be:
- 2a. `Anonymous Type`
- 2b. `Class Instance`
- 2c. `ExpandoObject`
- 2d. `Dictionary<string, TValue>`
In addition, to make your life easier, our library automatically registers and lets you use inside your expression:
- Member names in the case of:
- 2a. `Anonymous Type`
- 2b. `Class Instance`
- 2c. `ExpandoObject`
- Key names in the case of:
- 2d. `Dictionary<string, TValue>`
See more: https://eval-expression.net/eval-execute
*/
using System;
using System.Collections.Generic;
using System.Dynamic;
using Z.Expressions;
public class Program
{
public static void Main()
{
// 2a. `Anonymous Type` (example 1)
{
var expression = "return new List<int>() { 1, 2, 3, 4, 5 }.Where(x => x > MinValue && x < MaxValue)";
var list2a1 = Eval.Execute<List<int>>(expression, new { MinValue = 1, MaxValue = 5 });
FiddleHelper.WriteTable("2a. `Anonymous Type` (example 1)", list2a1);
}
// 2a. `Anonymous Type` (example 2)
{
var minValue = 1;
var maxValue = 5;
var expression = "return new List<int>() { 1, 2, 3, 4, 5 }.Where(x => x > minValue && x < maxValue)";
var list2a2 = Eval.Execute<List<int>>(expression, new { minValue, maxValue });
FiddleHelper.WriteTable("2a. `Anonymous Type` (example 2)", list2a2);
}
// 2b. `Class Instance`
{
var minMaxValue = new MinMaxValue() { MinValue = 1, MaxValue = 5 };
var expression = "return new List<int>() { 1, 2, 3, 4, 5 }.Where(x => x > MinValue && x < MaxValue)";
var list2b = Eval.Execute<List<int>>(expression, minMaxValue);
FiddleHelper.WriteTable("2b. `Class Instance`", list2b);
}
// 2c. `ExpandoObject`
{
dynamic expando = new ExpandoObject();
expando.MinValue = 1;
expando.MaxValue = 5;
var expression = "return new List<int>() { 1, 2, 3, 4, 5 }.Where(x => x > MinValue && x < MaxValue)";
var list2c = Eval.Execute<List<int>>(expression, expando);
FiddleHelper.WriteTable("2c. `ExpandoObject`", list2c);
}
// 2d. `Dictionary<string, TValue>`
{
var dict = new Dictionary<string, object>();
dict["MinValue"] = 1;
dict["MaxValue"] = 5;
var expression = "return new List<int>() { 1, 2, 3, 4, 5 }.Where(x => x > MinValue && x < MaxValue)";
var list2d = Eval.Execute<List<int>>(expression, dict);
FiddleHelper.WriteTable("2d. `Dictionary<string, TValue>`", list2d);
}
}
public class MinMaxValue
{
public int MinValue { get; set; }
public int MaxValue { get; set; }
}
}