DEV Community

Cover image for C# - Creating Expression Trees for Dynamic Query Generation
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Creating Expression Trees for Dynamic Query Generation

Expression trees in C# allow you to represent code as data structures, enabling you to build and manipulate code dynamically. This is particularly useful for scenarios where you need to create dynamic queries for databases or APIs.

Here's a simplified example of using expression trees to build a dynamic filter:

using System.Linq.Expressions;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        var people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 },
            new Person { Name = "Charlie", Age = 35 },
        };

        // Define a dynamic filter using an expression tree
        var filter = BuildFilter<Person>(p => p.Age > 30);

        // Apply the dynamic filter
        var filteredPeople = people.Where(filter.Compile());

        foreach (var person in filteredPeople)
        {
            Console.WriteLine($"{person.Name}, Age: {person.Age}");
        }
    }

    public static Expression<Func<T, bool>> BuildFilter<T>(Expression<Func<T, bool>> predicate)
    {
        return predicate;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We define a Person class to represent individuals with a Name and Age.
  • We create a list of Person objects.
  • We use expression trees to define a dynamic filter, which is a predicate that checks if a person's age is greater than 30.
  • We apply the filter using the Where method from LINQ.

Expression trees can be very powerful for constructing complex queries dynamically, and they are commonly used in Entity Framework for building database queries. You can build dynamic filters, sorting criteria, and projections by constructing expression trees programmatically, allowing for flexible and efficient querying of data sources.

Top comments (0)