### Setup License from Code (C#) Source: https://github.com/zzzprojects/eval-expression.net/wiki/PRO-License Provides a C# code example for adding the license name and key directly within the application code using the `EvalManager.AddLicense` method. Ensure to include the `Z.Expressions` namespace. This must be called before any library usage to avoid starting the monthly trial. ```csharp // using Z.Expressions; string licenseName = //... PRO license name string licenseKey = //... PRO license key EvalManager.AddLicense(licenseName, licenseKey); ``` -------------------------------- ### Setup License from Config File (C#) Source: https://github.com/zzzprojects/eval-expression.net/wiki/PRO-License Demonstrates how to configure the license name and key within the app.config or web.config file using the appSettings section. This method is recommended for storing license information. Requires version 1.0.32 or higher. ```xml ``` -------------------------------- ### Install Eval-Expression.NET NuGet Package Source: https://github.com/zzzprojects/eval-expression.net/wiki/Getting-Started This command demonstrates how to install the Eval-Expression.NET library using the Package Manager Console in Visual Studio. This package provides the functionality to evaluate and compile C# code at runtime. The free version is limited to 50 characters. ```powershell PM> Install-Package Z.Expressions.Eval ``` -------------------------------- ### Validate License Status (C#) Source: https://github.com/zzzprojects/eval-expression.net/wiki/PRO-License Shows how to check if the currently configured license is valid using the `EvalManager.ValidateLicense.ValidateLicense` method in C#. If the license is invalid, it returns an error message that can be used to throw an exception. ```csharp string licenseErrorMessage; if (!Z.Expressions.EvalManager.ValidateLicense.ValidateLicense(out licenseErrorMessage)) { throw new Exception(licenseErrorMessage); } ``` -------------------------------- ### C# Dynamic LINQ Count and Sum Aggregations Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Demonstrates counting elements and summing properties using string-based LINQ expressions with Eval-Expression.NET. Supports simple counts, counts with predicates, simple sums, sums with projections, and grouped sums. ```csharp using Z.Expressions; using System.Linq; // Count with predicate int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int evenCount = numbers.Count(n => "n % 2 == 0"); // Returns: 5 var products = GetProductList(); int beverageCount = products.Count(p => "p.Category == 'Beverages'"); // Returns: 12 // Simple sum int total = numbers.Execute("Sum()"); // Returns: 45 // Sum with projection string[] words = { "cherry", "apple", "blueberry" }; int totalCharacters = words.Execute("Sum(w => w.Length)"); // Returns: 20 decimal inventoryValue = products.Execute( "Sum(p => p.UnitPrice * p.UnitsInStock)" ); // Returns total value of all inventory // Grouped sum var categoryTotals = products.Execute( @"GroupBy(p => p.Category) .Select(g => new { Category = g.Key, TotalStock = g.Sum(p => p.UnitsInStock), TotalValue = g.Sum(p => p.UnitPrice * p.UnitsInStock) })" ); ``` -------------------------------- ### Eval.Compile - Pre-compiled Expression Delegates Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Compiles C# expressions into strongly-typed delegates for efficient, repeated execution. This is ideal for performance-critical applications where the same expression needs to be evaluated multiple times. ```APIDOC ## Eval.Compile - Pre-compiled Expression Delegates ### Description Compiles C# expressions into strongly-typed delegates for repeated execution with minimal overhead. Ideal for performance-critical scenarios requiring multiple evaluations. ### Method `Eval.Compile(string expression, params string[] parameterNames)` ### Endpoint N/A (This is a library function, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using Z.Expressions; // Compile a reusable calculation delegate var compiled = Eval.Compile>("X + Y", "X", "Y"); // Execute multiple times with different values int result1 = compiled(5, 3); // Returns: 8 int result2 = compiled(10, 20); // Returns: 30 int result3 = compiled(100, 50); // Returns: 150 // Compile complex business logic var priceCalculator = Eval.Compile>( "price * (1 + taxRate) - discount", "price", "taxRate", "discount" ); decimal finalPrice1 = priceCalculator(100M, 0.15M, 10M); // Returns: 105.00 decimal finalPrice2 = priceCalculator(200M, 0.20M, 25M); // Returns: 215.00 // String manipulation with compile var formatter = Eval.Compile>( "firstName + \" \" + lastName.ToUpper()", "firstName", "lastName" ); string fullName = formatter("John", "Smith"); // Returns: "John SMITH" ``` ### Response #### Success Response (200) - **TDelegate** (type) - A compiled delegate that can be invoked to execute the expression. ``` -------------------------------- ### C# Dynamic LINQ Select and Order Source: https://github.com/zzzprojects/eval-expression.net/wiki/LINQ-Dynamic Illustrates dynamic selection and ordering in LINQ using Eval-Expression.NET. It covers dynamic projection using 'SelectDynamic' and dynamic sorting using 'OrderByDynamic', including examples with and without parameters. ```csharp var list = new List() { 5, 2, 4, 1, 3 }; var list2 = list.SelectDynamic(x => "new { y = x + 1 }"); var list3 = list.SelectDynamic(x => "new { y = x + 1 }", new { y = 1 }); ``` ```csharp var list = new List() { 5, 2, 4, 1, 3 }; var list2 = list.OrderByDynamic(x => "x + 1"); var list3 = list.OrderByDynamic(x => "x + Y", new { Y = 1 }); ``` -------------------------------- ### Compile C# Expressions with Eval.Compile Source: https://github.com/zzzprojects/eval-expression.net/blob/master/NuGet.md Illustrates the Eval.Compile method for pre-compiling C# expressions into delegates for repeated execution. Examples cover compiling into Func and Action delegates, and how to use named parameters during compilation for improved readability and flexibility. ```csharp // Delegate Func var compiled = Eval.Compile>("{0} + {1}"); int result = compiled(1, 2); // Delegate Action var compiled = Eval.Compile>("{0} + {1}"); compiled(1, 2); // Named Parameter var compiled = Eval.Compile>("X + Y", "X", "Y"); int result = compiled(1, 2); ``` -------------------------------- ### Dynamic LINQ Where Clause with Eval-Expression.NET Source: https://github.com/zzzprojects/eval-expression.net/wiki/vs-LINQ-Dynamic-Query-Library This example demonstrates how to use Eval-Expression.NET to dynamically filter a list using a 'Where' clause with a simple condition and a condition with a variable. It requires the Z.Expressions namespace. ```csharp // using Z.Expressions; // Don't forget to include this. var list = new List() { 1, 2, 3, 4, 5 }; var list2 = list.Where(x => "x > 2"); var list3 = list.Where(x => "x > y", new { y = 2 }); ``` -------------------------------- ### Configure Custom Cache for EvalManager Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalManager Demonstrates how to set a custom cache for compiled lambda expressions by assigning an instance of a class inheriting from System.Runtime.Caching.ObjectCache to EvalManager.Cache. This allows for custom caching strategies for expression evaluation. ```csharp // using Z.Expressions; // Don't forget to include this. EvalManager.Cache = MemoryCache.Default; ``` -------------------------------- ### Compile C# Expression with Eval.Compile Source: https://github.com/zzzprojects/eval-expression.net/wiki/Getting-Started This example shows how to compile a C# expression string into a delegate using `Eval.Compile`. This is useful for performance-critical scenarios where an expression needs to be evaluated multiple times. The compiled delegate can then be invoked repeatedly. Ensure the `Z.Expressions` namespace is included. The free version is limited to 50 characters. ```csharp // using Z.Expressions; // Don't forget to include this. string code = "Price * Quantity"; var compiled = Eval.Compile>(code); decimal totals = 0; foreach(var order in orders) { totals += compiled(order); } ``` -------------------------------- ### Data Model Classes - Product, Customer, Order Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Defines C# classes for Product, Customer, and Order entities, representing common domain models. These classes are used to demonstrate real-world query scenarios, including filtering and selecting data across related entities using dynamic LINQ. The `Execute` method is used for applying string-based LINQ expressions to collections of these objects. ```csharp using System; using System.Collections.Generic; // Product entity public class Product { public int ProductID { get; set; } public string ProductName { get; set; } public string Category { get; set; } public decimal UnitPrice { get; set; } public int UnitsInStock { get; set; } } // Customer entity with related orders public class Customer { public string CustomerID { get; set; } public string CompanyName { get; set; } public string City { get; set; } public string Region { get; set; } public string Country { get; set; } public Order[] Orders { get; set; } } // Order entity public class Order { public int OrderID { get; set; } public DateTime OrderDate { get; set; } public decimal Total { get; set; } } // Sample data generation var products = new List { new Product { ProductID = 1, ProductName = "Chai", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 39 }, new Product { ProductID = 2, ProductName = "Chang", Category = "Beverages", UnitPrice = 19.0000M, UnitsInStock = 17 }, new Product { ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments", UnitPrice = 10.0000M, UnitsInStock = 13 } }; // Query across related entities var customersWithOrders = customers.Execute>( "Where(c => c.Orders.Length > 0)" ); // Filter by nested property var highValueOrders = customers.Execute( @"SelectMany(c => c.Orders) .Where(o => o.Total > 1000) .OrderByDescending(o => o.Total)" ); ``` -------------------------------- ### Dynamic LINQ Any and All - Existential Quantifiers Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Demonstrates the use of dynamic LINQ's `Any` and `All` extension methods, which test collections against string-based predicates. These methods return a boolean indicating if at least one element satisfies the condition (`Any`) or if all elements satisfy it (`All`). They are useful for concise conditional checks on collections, including complex criteria involving multiple properties. ```csharp using Z.Expressions; using System.Linq; // Check if any element matches condition int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; bool hasNegative = numbers.Any(n => "n < 0"); // Returns: false bool hasEven = numbers.Any(n => "n % 2 == 0"); // Returns: true // Check if all elements match condition bool allPositive = numbers.All(n => "n >= 0"); // Returns: true bool allEven = numbers.All(n => "n % 2 == 0"); // Returns: false // Product queries var products = GetProductList(); bool anyOutOfStock = products.Any(p => "p.UnitsInStock == 0"); // Returns: true if any products are out of stock bool allAffordable = products.All(p => "p.UnitPrice < 100"); // Returns: false (some products exceed 100) // Complex conditions bool hasExpensiveSeafood = products.Any( p => "p.Category == 'Seafood' && p.UnitPrice > 50" ); ``` -------------------------------- ### OrderByDynamic for String-Based Sorting Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Sorts collections using string-based key selector expressions, enabling dynamic sorting logic. This method supports custom comparers for specialized sorting requirements, such as case-insensitive ordering. Dependencies include the Z.Expressions library. ```csharp using Z.Expressions; // Sort strings alphabetically string[] words = { "cherry", "apple", "blueberry" }; var sortedWords = words.OrderByDynamic(w => "w"); // Returns: ["apple", "blueberry", "cherry"] // Sort by property var sortedByLength = words.OrderByDynamic(w => "w.Length"); // Returns: ["apple", "cherry", "blueberry"] (5, 6, 9 chars) // Sort custom objects var products = GetProductList(); var sortedProducts = products.OrderByDynamic(p => "p.ProductName"); // Returns products sorted alphabetically by name // Case-insensitive sorting with custom comparer string[] mixedCase = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; var sorted = mixedCase.OrderByDynamic(a => "a", new CaseInsensitiveComparer()); // Returns: ["AbAcUs", "aPPLE", "BlUeBeRrY", "bRaNcH", "cHeRry", "ClOvEr"] public class CaseInsensitiveComparer : IComparer { public int Compare(string x, string y) { return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); } } ``` -------------------------------- ### Eval.Execute - Direct Expression Execution Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Evaluates and executes C# code expressions directly at runtime. This method is suitable for one-time evaluations and supports various parameter types including anonymous objects, positional arguments, and dynamic objects. ```APIDOC ## Eval.Execute - Direct Expression Execution ### Description Evaluates and executes C# code expressions at runtime, returning the computed result. Supports anonymous objects, positional arguments, and class members as parameter sources. ### Method `Eval.Execute(string expression, params object[] args)` ### Endpoint N/A (This is a library function, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using Z.Expressions; // Simple arithmetic with anonymous object parameters int result = Eval.Execute("X + Y", new { X = 1, Y = 2 }); // Returns: 3 // Using positional parameters int sum = Eval.Execute("{0} + {1}", 10, 20); // Returns: 30 // Complex expressions with LINQ int filtered = Eval.Execute(@" var list = new List() { 1, 2, 3, 4, 5 }; var filter = list.Where(x => x < 4); return filter.Sum(x => x);"); // Returns: 6 // With ExpandoObject for dynamic properties dynamic expandoObject = new ExpandoObject(); expandoObject.Price = 100; expandoObject.Tax = 0.15M; decimal total = Eval.Execute("Price * (1 + Tax)", expandoObject); // Returns: 115.00 ``` ### Response #### Success Response (200) - **T** (type) - The result of the evaluated expression. ``` -------------------------------- ### ObjectDumper.Write - Debug Output Utility Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Utilizes the `My.ObjectDumper.Write` method to format and output object hierarchies to a `StringBuilder` for debugging. This utility handles nested collections and complex object graphs, allowing for controlled depth when displaying data. It's useful for inspecting query results and application state. ```csharp using System.Text; var sb = new StringBuilder(); var products = GetProductList(); // Dump collection of objects My.ObjectDumper.Write(sb, products); // Output: // ProductID=1 ProductName=Chai Category=Beverages UnitPrice=18.0000 UnitsInStock=39 // ProductID=2 ProductName=Chang Category=Beverages UnitPrice=19.0000 UnitsInStock=17 // ... // Dump with depth control for nested objects var customers = GetCustomerList(); My.ObjectDumper.Write(sb, customers, depth: 2); // Displays customers with their orders up to 2 levels deep // Dump query results var categoryGroups = products.Execute( "GroupBy(p => p.Category).Select(g => new { Category = g.Key, Count = g.Count() })" ); My.ObjectDumper.Write(sb, categoryGroups); // Output: // Category=Beverages Count=12 // Category=Condiments Count=12 // Category=Confections Count=13 // ... string output = sb.ToString(); ``` -------------------------------- ### Register Extension Methods with EvalContext - C# Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalContext Demonstrates how to use EvalContext to register extension methods for use in evaluated expressions. This example registers methods from Z.ExtensionMethods and then executes an expression utilizing an extension method. ```csharp // using Z.Expressions; // Don't forget to include this. var context = new EvalContext(); context.RegisterExtensionMethod(typeof(Z.ExtensionMethods)); bool result = Eval.Execute("X.In(1, 2, 3)", new { X = 1 }); ``` -------------------------------- ### Execute Dynamic LINQ Queries with Z.Expressions Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Executes complete LINQ query chains represented as string expressions on collections. This method allows for the dynamic construction of complex queries without requiring compile-time lambda expressions. It supports filtering, projection, and aggregation operations. ```csharp using Z.Expressions; // Simple Where query int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var filtered = numbers.Execute>("Where(n => n < 5)"); // Returns: [4, 1, 3, 2, 0] // Chained Where and Select var transformed = numbers.Execute>("Where(n => n < 5).Select(n => n * 10)"); // Returns: [40, 10, 30, 20, 0] // Complex product queries var products = GetProductList(); var soldOutProducts = products.Execute>( "Where(prod => prod.UnitsInStock == 0)" ); // Aggregate operations with Execute int[] nums = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var sum = nums.Execute("Sum()"); // Returns: 45 // String aggregation with projection string[] words = { "cherry", "apple", "blueberry" }; var totalChars = words.Execute("Sum(w => w.Length)"); // Returns: 20 // GroupBy with projection var categoryTotals = products.Execute( "GroupBy(p => p.Category).Select(g => new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.UnitsInStock) })" ); ``` -------------------------------- ### Modify Default EvalContext Configuration Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalManager Shows how to change the default configuration for all evaluation contexts using EvalManager.DefaultContext. This includes registering extension methods and modifying binding flags for case-insensitive member access. These changes affect static evaluation methods and extension methods. ```csharp // using Z.Expressions; // Don't forget to include this. EvalManager.DefaultContext.RegisterExtensionMethod(typeof(Z.ExtensionMethods)) // Make member case insensitive (Math.pOW = Math.Pow) EvalManager.DefaultContext.BindingFlags = BindingFlags.IgnoreCase | context.BindingFlags ``` -------------------------------- ### Dynamic LINQ Where - Filter with String Expressions Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Filters collections using string-based predicate expressions that are evaluated at runtime. This allows for dynamic filtering logic defined as strings, similar to lambda expressions but evaluated dynamically. ```APIDOC ## Dynamic LINQ Where - Filter with String Expressions ### Description Filters collections using string-based predicate expressions evaluated at runtime. Accepts lambda expressions as strings instead of compiled delegates. ### Method `Enumerable.Where(this IEnumerable source, string predicate)` ### Endpoint N/A (This is an extension method for `IEnumerable`, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using Z.Expressions; using System.Linq; // Simple numeric filtering int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = numbers.Where(n => "n < 5"); // Returns: [4, 1, 3, 2, 0] // Filter products by property var products = new List { new Product { ProductName = "Chai", UnitsInStock = 39, UnitPrice = 18.00M }, new Product { ProductName = "Chang", UnitsInStock = 17, UnitPrice = 19.00M }, new Product { ProductName = "Gumbo Mix", UnitsInStock = 0, UnitPrice = 21.35M } }; var soldOut = products.Where(prod => "prod.UnitsInStock == 0"); // Returns: [Gumbo Mix] // Complex conditions with multiple properties var expensiveInStock = products.Where(p => "p.UnitsInStock > 0 && p.UnitPrice > 18.00M"); // Returns: [Chang] // String comparison with nested properties var customers = GetCustomerList(); var waCustomers = customers.Where(cust => "cust.Region == 'WA'"); // Returns all customers where Region equals "WA" ``` ### Response #### Success Response (200) - **IEnumerable** (type) - An `IEnumerable` that contains elements from the input sequence that satisfy the predicate. ``` -------------------------------- ### Customize BindingFlags for Member Retrieval (C#) Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalContext-Options Modify the default BindingFlags to alter how members (Constructor, Method, Property, Field) are retrieved during compilation. This example demonstrates making member lookup case-insensitive. ```csharp // using Z.Expressions; // Don't forget to include this. var context = new EvalContext(); // Make member case insensitive (Math.pOW = Math.Pow) context.BindingFlags = BindingFlags.IgnoreCase | context.BindingFlags ``` -------------------------------- ### Eval.Execute: Direct C# Expression Evaluation with Parameters (C#) Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Evaluates and executes C# code expressions directly at runtime using the Eval.Execute method. It supports anonymous objects, positional parameters, and dynamic objects (ExpandoObject) as sources for expression variables. Useful for one-time evaluations where pre-compilation is not necessary. ```csharp using Z.Expressions; // Simple arithmetic with anonymous object parameters int result = Eval.Execute("X + Y", new { X = 1, Y = 2 }); // Returns: 3 // Using positional parameters int sum = Eval.Execute("{0} + {1}", 10, 20); // Returns: 30 // Complex expressions with LINQ int filtered = Eval.Execute("\ var list = new List() { 1, 2, 3, 4, 5 }; var filter = list.Where(x => x < 4); return filter.Sum(x => x);"); // Returns: 6 // With ExpandoObject for dynamic properties dynamic expandoObject = new ExpandoObject(); expandoObject.Price = 100; expandoObject.Tax = 0.15M; decimal total = Eval.Execute("Price * (1 + Tax)", expandoObject); // Returns: 115.00 ``` -------------------------------- ### Eval.Compile: Pre-compiled C# Expression Delegates for Reuse (C#) Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Compiles C# expressions into strongly-typed delegates using Eval.Compile, enabling efficient, repeated execution with minimal overhead. This is ideal for performance-critical scenarios. It allows defining parameters explicitly, supporting various delegate types for complex logic and string manipulations. ```csharp using Z.Expressions; // Compile a reusable calculation delegate var compiled = Eval.Compile>("X + Y", "X", "Y"); // Execute multiple times with different values int result1 = compiled(5, 3); // Returns: 8 int result2 = compiled(10, 20); // Returns: 30 int result3 = compiled(100, 50); // Returns: 150 // Compile complex business logic var priceCalculator = Eval.Compile>( "price * (1 + taxRate) - discount", "price", "taxRate", "discount" ); decimal finalPrice1 = priceCalculator(100M, 0.15M, 10M); // Returns: 105.00 decimal finalPrice2 = priceCalculator(200M, 0.20M, 25M); // Returns: 215.00 // String manipulation with compile var formatter = Eval.Compile>( "firstName + \" \" + lastName.ToUpper()", "firstName", "lastName" ); string fullName = formatter("John", "Smith"); // Returns: "John SMITH" ``` -------------------------------- ### SelectDynamic for String-Based Projections Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Projects collection elements into new forms using string-based selector expressions, returning dynamic types that require runtime type resolution. This is useful for creating anonymous types or transforming data based on dynamic criteria. Dependencies include the Z.Expressions library. ```csharp using Z.Expressions; // Simple transformation int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var numsPlusOne = numbers.SelectDynamic(n => "n + 1"); // Returns: [6, 5, 2, 4, 10, 9, 7, 8, 3, 1] // Extract property values var products = GetProductList(); var productNames = (IEnumerable)products.SelectDynamic(p => "p.ProductName"); // Returns: ["Chai", "Chang", "Aniseed Syrup", ...] // Anonymous type projection string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" }; dynamic upperLowerWords = words.SelectDynamic( word => "new { Upper = word.ToUpper(), Lower = word.ToLower() }" ); foreach (var ul in upperLowerWords) { Console.WriteLine($"Uppercase: {ul.Upper}, Lowercase: {ul.Lower}"); } // Output: // Uppercase: APPLE, Lowercase: apple // Uppercase: BLUEBERRY, Lowercase: blueberry // Uppercase: CHERRY, Lowercase: cherry // Complex projection with external variables int[] nums = { 5, 4, 1, 3, 9 }; string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; dynamic digitOddEvens = nums.SelectDynamic( n => "new { Digit = strings[n], Even = (n % 2 == 0) }", new { strings } ); // Returns dynamic collection with Digit and Even properties // Indexed selection dynamic numsInPlace = numbers.SelectDynamic( (num, index) => "new { Num = num, InPlace = (num == index) }" ); ``` -------------------------------- ### Dynamic LINQ GroupJoin - Hierarchical Joins Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Performs group join operations using dynamic string expressions with the Z.Expressions library. It creates hierarchical result sets by joining collections based on specified keys and projecting new anonymous types. The output is an enumerable of objects, each containing a category and a collection of associated products. ```csharp using Z.Expressions; string[] categories = { "Beverages", "Condiments", "Vegetables", "Dairy Products", "Seafood" }; var products = GetProductList(); // Group products by category dynamic result = categories.Execute( "GroupJoin(products, c => c, p => p.Category, (c, ps) => new { Category = c, Products = ps })", new { products } ); foreach (var categoryGroup in result) { Console.WriteLine($"{categoryGroup.Category}:"); foreach (var product in categoryGroup.Products) { Console.WriteLine($" {product.ProductName}"); } } ``` -------------------------------- ### Dynamic LINQ Where: Filtering Collections with String Expressions (C#) Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Filters collections using string-based predicate expressions evaluated at runtime via the dynamic LINQ extension method 'Where'. This allows for flexible filtering logic defined as strings, integrating seamlessly with LINQ queries. It supports simple and complex conditions involving multiple properties and data types. ```csharp using Z.Expressions; using System.Linq; // Simple numeric filtering int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = numbers.Where(n => "n < 5"); // Returns: [4, 1, 3, 2, 0] // Filter products by property var products = new List { new Product { ProductName = "Chai", UnitsInStock = 39, UnitPrice = 18.00M }, new Product { ProductName = "Chang", UnitsInStock = 17, UnitPrice = 19.00M }, new Product { ProductName = "Gumbo Mix", UnitsInStock = 0, UnitPrice = 21.35M } }; var soldOut = products.Where(prod => "prod.UnitsInStock == 0"); // Returns: [Gumbo Mix] // Complex conditions with multiple properties var expensiveInStock = products.Where(p => "p.UnitsInStock > 0 && p.UnitPrice > 18.00M"); // Returns: [Chang] // String comparison with nested properties var customers = GetCustomerList(); var waCustomers = customers.Where(cust => "cust.Region == 'WA'"); // Returns all customers where Region equals "WA" ``` -------------------------------- ### Register Custom Types with EvalManager Source: https://context7.com/zzzprojects/eval-expression.net/llms.txt Registers custom types with the evaluation context using `EvalManager.DefaultContext.RegisterType`. This enables the instantiation and usage of these custom types within dynamic expressions evaluated by the Z.Expressions library. It's essential for using custom comparers or business logic classes in dynamic queries. ```csharp using Z.Expressions; // Register a custom comparer for use in expressions EvalManager.DefaultContext.RegisterType(typeof(CaseInsensitiveComparer)); string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY" }; var sortedWords = words.Execute( "OrderBy(a => a, new CaseInsensitiveComparer())" ); // Successfully creates CaseInsensitiveComparer instance within expression // Register custom business classes public class DiscountCalculator { public decimal Calculate(decimal price, decimal rate) => price * (1 - rate); } EvalManager.DefaultContext.RegisterType(typeof(DiscountCalculator)); var discountedPrice = Eval.Execute( @"var calc = new DiscountCalculator(); return calc.Calculate(100, 0.15);"); // Returns: 85.00 ``` -------------------------------- ### EvalContext BindingFlags Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalContext-Options Modify the default BindingFlags used to retrieve members (Constructor, Method, Property, Field) within the expression evaluation context. This allows for case-insensitive member access, for example. ```APIDOC ## EvalContext BindingFlags ### Description Allows customization of `BindingFlags` used to retrieve members (Constructor, Method, Property, and Field) in the evaluation context. A common use case is to enable case-insensitive matching. ### Method Property Set ### Endpoint N/A (Code-based configuration) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp // using Z.Expressions; var context = new EvalContext(); // Make member case insensitive (e.g., Math.pOW will match Math.Pow) context.BindingFlags = BindingFlags.IgnoreCase | context.BindingFlags; ``` ### Response #### Success Response (200) N/A (Configuration change) #### Response Example N/A ``` -------------------------------- ### Evaluate Arithmetic Expressions in C# Source: https://github.com/zzzprojects/eval-expression.net/wiki/Tutorials-&-Examples Demonstrates how to evaluate basic arithmetic and mathematical expressions using the Eval-Expression.NET library. It takes a string expression as input and returns the calculated result. No external dependencies beyond the library itself are required. ```csharp using Eval.Extensions; public class Example { public static void Main(string[] args) { string expression = "(10 + 2) * 3 / 2"; object result = expression.Eval(); // result = 18 string mathExpression = "Abs(Cos(Pi / 2)) + Pow(2, 3)"; object mathResult = mathExpression.Eval(); // mathResult = 9.0 } } ``` -------------------------------- ### C# Dynamic LINQ vs Static LINQ Source: https://github.com/zzzprojects/eval-expression.net/wiki/LINQ-Dynamic Demonstrates the basic usage of Eval-Expression.NET by comparing a static LINQ query with a dynamic LINQ query using the same filtering logic. This highlights how to represent LINQ expressions as strings for dynamic execution. ```csharp var list = new List() { 1, 2, 3, 4, 5 }; var linqStatic = list.Where(x => x > 2); var linqDynamic = list.Where(x => "x > 2"); ``` -------------------------------- ### Dynamic LINQ Operations: OrderBy, Select, Where with Eval-Expression.NET and LINQ Dynamic Query Library Source: https://github.com/zzzprojects/eval-expression.net/wiki/vs-LINQ-Dynamic-Query-Library This snippet showcases the syntax differences for OrderBy, Select, and Where operations between Eval-Expression.NET and LINQ Dynamic Query Library. Eval-Expression.NET uses a LINQ-like syntax with dynamic methods, while LINQ Dynamic Query Library uses a string-based approach. ```csharp // Eval-Expression.NET examples: // var orderedList = data.OrderByDynamic(x => "x.Property1"); // var selectedData = data.SelectDynamic(x => "new { Y = x.Property1, x.Property2 }"); // var filteredList = data.Where(x => "x.Property1 == 1 && x.Property2 == 2"); // LINQ Dynamic Query Library examples: // var orderedList = data.OrderBy("Property1"); // var selectedData = data.Select("new(Property1 as Y, Property2)"); // var filteredList = data.Where("Property1 = 1 and Property2 = 2"); ``` -------------------------------- ### Implement Fast Getter-Setter in C# Source: https://github.com/zzzprojects/eval-expression.net/wiki/Tutorials-&-Examples Illustrates how Eval-Expression.NET can be used to create fast getter and setter methods for object properties without explicit reflection. This can improve performance by pre-compiling accessors. Requires an object instance and the property name. ```csharp using System; using Eval.Extensions; public class Person { public string Name { get; set; } } public class Example { public static void Main(string[] args) { var person = new Person { Name = "John Doe" }; // Fast getter var getName = person.GetMember("Name"); string name = (string)getName(); Console.WriteLine(name); // Output: John Doe // Fast setter var setName = person.SetMember("Name"); setName("Jane Doe"); Console.WriteLine(person.Name); // Output: Jane Doe } } ``` -------------------------------- ### Change Cache Key Prefix for Compiled Expressions (C#) Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalContext-Options Customize the prefix used for caching compiled expressions. Assigning a new value, such as a GUID, ensures that expressions compiled with different options use distinct cache entries. ```csharp // using Z.Expressions; // Don't forget to include this. var context = new EvalContext(); context.CacheKey = Guid.NewGuid().ToString(); ``` -------------------------------- ### Execute C# Code Snippet with Eval.Execute Source: https://github.com/zzzprojects/eval-expression.net/wiki/Getting-Started This snippet demonstrates how to execute a C# code string at runtime using the `Eval.Execute` method from the Eval-Expression.NET library. It takes a C# expression as a string and returns the result, strongly-typed to the specified generic type (int in this case). Ensure the `Z.Expressions` namespace is included. The free version is limited to 50 characters. ```csharp // using Z.Expressions; // Don't forget to include this. int result = Eval.Execute( @" var list = new List() { 1, 2, 3, 4, 5 }; var filter = list.Where(x => x < 3); return filter.Sum(x => x); "); ``` -------------------------------- ### Evaluate C# Expressions with Eval.Execute Source: https://github.com/zzzprojects/eval-expression.net/blob/master/NuGet.md Demonstrates the Eval.Execute method for evaluating C# expressions at runtime. It shows how to pass parameters using anonymous types, argument positions, class members, and dictionary keys. This method is suitable for single evaluations where pre-compilation is not necessary. ```csharp // Parameter: Anonymous Type int result = Eval.Execute("X + Y", new { X = 1, Y = 2} ); // Parameter: Argument Position int result = Eval.Execute("{0} + {1}", 1, 2); // Parameter: Class Member dynamic expandoObject = new ExpandoObject(); expandoObject.X = 1; expandoObject.Y = 2; int result = Eval.Execute("X + Y", expandoObject); // Parameter: Dictionary Key var values = new Dictionary() { {"X", 1}, {"Y", 2} }; int result = Eval.Execute("X + Y", values); ``` -------------------------------- ### Execute Dynamic C# Code with EvalContext Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalContext-Compile-&-Execute This snippet demonstrates how to execute dynamic C# code within an instance context using the EvalContext class. It supports various overloads for specifying return types, parameters, and code strings. Ensure the Z.Expressions namespace is included. ```csharp // using Z.Expressions; // Don't forget to include this. var context = new EvalContext(); // ... context options ... string code = "Price * Quantity"; var price = context.Execute(code, orderItem); ``` -------------------------------- ### Execute Expression using Extension Method in C# Source: https://github.com/zzzprojects/eval-expression.net/blob/master/README.md Demonstrates executing a C# expression string directly as an extension method on the string itself. This provides a concise syntax for evaluating expressions. It requires the Z.Expressions.Eval NuGet package. ```csharp // @nuget: Z.Expressions.Eval using Z.Expressions; string s = "X + Y"; int result = s.Execute(new { X = 1, Y = 2 }); ``` -------------------------------- ### EvalContext Clone Method Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalContext-Options Create a shallow copy of the current `EvalContext`. This is useful for preserving existing settings and then modifying specific options for a new evaluation scope. ```APIDOC ## EvalContext Clone Method ### Description Provides a method to create a shallow copy of the current `EvalContext` object. This is particularly useful for duplicating all existing settings, including registered types, and then applying specific modifications for a new expression evaluation scenario. ### Method Instance Method ### Endpoint N/A (Code-based operation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp // using Z.Expressions; var context = EvalManager.DefaultContext.Clone(); ``` ### Response #### Success Response (200) Returns a new `EvalContext` object that is a shallow copy of the original. #### Response Example ```json { "__type": "EvalContext", "//": "This is a representation of a cloned EvalContext. Specific fields depend on the original context's configuration." } ``` ``` -------------------------------- ### Execute Simple Math Expression in C# Source: https://github.com/zzzprojects/eval-expression.net/blob/master/README.md Evaluates a simple C# math expression with predefined variables. It uses the Eval.Execute method and requires the Z.Expressions.Eval NuGet package. The input is a string expression and an anonymous object containing variables, and the output is the integer result of the expression. ```csharp // @nuget: Z.Expressions.Eval using Z.Expressions; int result = Eval.Execute("X + Y", new { X = 1, Y = 2}); ``` -------------------------------- ### Compile Expression using Extension Method in C# Source: https://github.com/zzzprojects/eval-expression.net/blob/master/README.md Compiles a C# expression string into a delegate using an extension method. This offers a clean syntax for preparing expressions for repeated evaluation. It requires the Z.Expressions.Eval NuGet package. ```csharp // @nuget: Z.Expressions.Eval using Z.Expressions; string s = "X + Y"; var compiled = s.Compile>("X", "Y"); foreach(var item in list) { int result = compiled(item.Value1, item.Value2); } ``` -------------------------------- ### Shallow Copy EvalContext (C#) Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalContext-Options Create a shallow copy of the current EvalContext using the `Clone` method. This is useful for preserving existing options and registered types while allowing modifications for specific expression evaluations. ```csharp // using Z.Expressions; // Don't forget to include this. var context = EvalManager.DefaultContext.Clone(); ``` -------------------------------- ### EvalContext CacheKeyPrefix Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalContext-Options Customize the prefix used for caching compiled expressions. Using distinct prefixes for different configurations ensures cache isolation and prevents conflicts. ```APIDOC ## EvalContext CacheKeyPrefix ### Description Allows customization of the prefix used for caching compiled expressions. It's recommended to use unique prefixes when different `EvalContext` options are employed to ensure proper cache management. ### Method Property Set ### Endpoint N/A (Code-based configuration) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp // using Z.Expressions; var context = new EvalContext(); context.CacheKey = Guid.NewGuid().ToString(); ``` ### Response #### Success Response (200) N/A (Configuration change) #### Response Example N/A ``` -------------------------------- ### Compile Dynamic C# Code with EvalContext Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalContext-Compile-&-Execute This snippet shows how to compile dynamic C# code into delegates using EvalContext. It allows specifying the delegate type and parameter names for the compiled code. The Z.Expressions namespace must be included. Compiled delegates can be invoked multiple times for efficiency. ```csharp // using Z.Expressions; // Don't forget to include this. var context = new EvalContext(); // ... context options ... string code = "Price * Quantity"; var compiled = context.Compile>(code); decimal totals = 0; foreach(var item in list) { totals += compiled(item); } ``` -------------------------------- ### Perform String Interpolation in C# Source: https://github.com/zzzprojects/eval-expression.net/wiki/Tutorials-&-Examples Demonstrates using Eval-Expression.NET for string interpolation, allowing dynamic construction of strings with embedded expressions. This feature is similar to standard C# interpolated strings but evaluated at runtime. Supports various data types and expressions within the string. ```csharp using System; using Eval.Extensions; public class Example { public static void Main(string[] args) { string name = "World"; int value = 42; // Basic interpolation string interpolatedString = $("Hello {name}!").Eval(); Console.WriteLine(interpolatedString); // Output: Hello World! // Interpolation with expressions string complexInterpolation = $("The answer is {value * 2}.").Eval(); Console.WriteLine(complexInterpolation); // Output: The answer is 84. // Interpolation with method calls string methodInterpolation = $("Today is {DateTime.Now.DayOfWeek}.").Eval(); Console.WriteLine(methodInterpolation); // Output: Today is [Current DayOfWeek]. } } ``` -------------------------------- ### Eval.Compile Source: https://github.com/zzzprojects/eval-expression.net/wiki/Eval-Compile Compiles a dynamic C# code into a delegate, accepting various parameter types for flexibility. ```APIDOC ## Eval.Compile ### Description Compiles a dynamic C# code into a delegate, supporting various overloads for defining input parameter types. This is useful when the exact types of parameters are known at compile time or when dealing with a variable number of parameters. ### Method `Eval.Compile(string code): Func `Eval.Compile(string code, Type type1): Func `Eval.Compile(string code, Type type1, ... , Type type9): Func `Eval.Compile(string code, IEnumerable types): Func `Eval.Compile(string code, params Type[] types): Func `Eval.Compile(string code, IDictionary nameTypes): Func ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp // Overload with explicit types (up to 9 parameters) var compiled1 = Eval.Compile("{0} + {1}", typeof(int), typeof(int)); object result1 = compiled1(1, 2); // result1 will be 3 // Overload with params Type[] var values = new List() {1, 2}; var types = values.Select(x => x.GetType()).ToArray(); var compiled2 = Eval.Compile("{0} + {1}", types); var result2 = compiled2(values); // result2 will be 3 // Overload with IDictionary for named parameters var valuesDict = new Dictionary {{"X", 1}, {"Y", 2}}; var typesDict = valuesDict.ToDictionary(x => x.Key, x => x.Value.GetType()); var compiled3 = Eval.Compile("X + Y", typesDict); var result3 = compiled3(valuesDict); // result3 will be 3 ``` ### Response #### Success Response (200) - **delegate** (delegate type) - A delegate representing the compiled C# expression. The return type is `object`, and the parameter types depend on the overload used. ``` -------------------------------- ### Evaluate Power Operator Expression with Parameters in C# Source: https://github.com/zzzprojects/eval-expression.net/wiki/Arithmetic-Exponent-Operator This C# code snippet demonstrates evaluating a dynamic arithmetic expression with the '^^' power operator and parameters using Eval-Expression.NET. The 'Z.Expressions' namespace must be included. Input includes the expression string and an anonymous object for parameters. ```csharp // using Z.Expressions; // Don't forget to include this. var result = Eval.Execute("X^^Y", new { X = 2, Y = 3 }); // return 8; ``` -------------------------------- ### Registering Context Information in Eval-Expression.NET Source: https://github.com/zzzprojects/eval-expression.net/wiki/EvalContext-Register-&-Unregister Demonstrates how to register various elements such as aliases, assemblies, extension methods, global constants, variables, and static members into an EvalContext. This allows for customized code evaluation by providing access to specific .NET features and user-defined elements. ```csharp // using Z.Expressions; // Don't forget to include this. var context = new EvalContext(); context.RegisterAlias("Math2", "System.Math"); context.RegisterAssembly(Assembly.GetEntryAssembly()); context.RegisterDomainAssemblies(); context.RegisterExtensionMethod(typeof(Enumerable)); context.RegisterExtensionMethod(whereMethodInfo, selectMethodInfo) context.RegisterGlobalConstant("sessionMax", 1000); context.RegisterGlobalVariable("sessionCount", 0); context.RegisterStaticMember(typeof(Math), typeof(Int)); context.RegisterStaticMember(powMemberInfo, RoundMemberInfo); context.RegisterType(typeof (bool), typeof(char); ```