3 AND..."/> 3 AND...">
Home >Backend Development >C++ >How can I dynamically evaluate LINQ expressions from strings in C#?
Dynamically Evaluating LINQ Expressions from Strings
Problem:
Given an input string representing a LINQ expression, such as "(Person.Age > 3 AND Person.Weight > 50) OR Person.Age < 3", the goal is to dynamically create a Func
Overbaked Approach:
The proposed solution involving ANTLR grammar and the Predicate Builder framework may be unnecessarily complex.
Alternative Solution: Dynamic LINQ
The Dynamic LINQ library provides an elegant and straightforward solution. Here's how to use it:
using System; using System.Linq.Expressions; using System.Linq.Dynamic; namespace ExpressionParser { class Program { public class Person { public string Name { get; set; } public int Age { get; set; } public int Weight { get; set; } public DateTime FavouriteDay { get; set; } } static void Main() { // Input expression string const string exp = @"(Person.Age > 3 AND Person.Weight > 50) OR Person.Age < 3"; // Compile expression into a lambda expression var p = Expression.Parameter(typeof(Person), "Person"); var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p }, null, exp); // Create a Person instance var bob = new Person { Name = "Bob", Age = 30, Weight = 213, FavouriteDay = new DateTime(2000, 1, 1) }; // Evaluate expression against the Person instance var result = e.Compile().DynamicInvoke(bob); // Print result Console.WriteLine(result); Console.ReadKey(); } } }
In this example, we dynamically parse the expression string into a lambda expression and then compile it into a Func Benefits of Dynamic LINQ: Note: Remember to include the System.Linq.Dynamic nuget package for this code to work. The above is the detailed content of How can I dynamically evaluate LINQ expressions from strings in C#?. For more information, please follow other related articles on the PHP Chinese website!