CSharp · Console
// C# Eval Expression
// Doc: https://eval-expression.net/my-first-evaluation
// @nuget: Z.Expressions.Eval
/*
## Evaluate a C# expression from a string
If you have taken the time to read and understand the first three sections of this tutorial, the rest should be straightforward.
Our library adds a syntactic sugar execute extension method to extend the string type. Passing parameters and return type are similar to what we have previously seen, and the only difference is the code is taken from the string that the method extends.
In that example, we will set our expression in a string variable and call the `Execute` method that extends it.
See more: https://eval-expression.net/my-first-evaluation
*/
using System;
using System.Dynamic;
using System.Collections.Generic;
using Z.Expressions;
public class Program
{
public static void Main()
{
var list = new List<int>() { 1, 2, 3, 4 };
var greaterThan = 2;
var expressionToExecute = "list.Where(x => x > greaterThan)";
list = expressionToExecute.Execute<List<int>>(new { list, greaterThan });
// SIMILAR TO: list = Eval.Execute<List<int>>("list.Where(x => x > greaterThan)", new { list, greaterThan });
FiddleHelper.WriteTable(list);
}
}