DEV Community

Cover image for C# - Dynamic Querying with Lambda Expressions and Expression Trees
Keyur Ramoliya
Keyur Ramoliya

Posted on

1

C# - Dynamic Querying with Lambda Expressions and Expression Trees

Lambda expressions and expression trees can be used to build dynamic queries at runtime. This is especially valuable when you want to construct complex queries based on user input or when dealing with dynamic data sources.

Here's an example:

using System;
using System.Collections.Generic;
using System.Linq;
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 },
        };

        // Create a dynamic query based on user input
        Expression<Func<Person, bool>> dynamicQuery = CreateDynamicQuery("Age", 30);

        // Apply the dynamic query to filter the data
        var filteredPeople = people.AsQueryable().Where(dynamicQuery);

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

    public static Expression<Func<Person, bool>> CreateDynamicQuery(string propertyName, int value)
    {
        var parameter = Expression.Parameter(typeof(Person), "p");
        var property = Expression.Property(parameter, propertyName);
        var constant = Expression.Constant(value);
        var body = Expression.GreaterThanOrEqual(property, constant);

        return Expression.Lambda<Func<Person, bool>>(body, parameter);
    }
}
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 dynamic query using a CreateDynamicQuery method that takes a property name and a value. This method builds an expression tree dynamically to represent the query condition (Age >= 30 in this case).

  • We use the dynamic query with Where to filter the list of people based on the user-defined criteria.

This approach allows you to construct queries dynamically based on user input or other runtime conditions, making your code more flexible and adaptable to various data filtering requirements. It's especially useful when building data-driven applications or systems where query criteria are not known at compile time.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
thomasouvre profile image
ouvré thomas

This approach may lead to performance issues : the internal cache of EF core will grow for every values of 'age' because the corresponding expression is a constant. So any different value will generate a new query efcore should compile and save in the cache.

The problem is the same with your database engine (at least with SQL server) : a constant value will be translated in ... A constant value in SQL. The correct version of the SQL querry should probably be parameterezid, so the compiled version of the query is put in cache one time.

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay