🏠 VisualStudioTutor.com  ·  C# Tutorial Home  ·  C# Lesson 33 of 40
Lesson 33 of 40 Advanced LINQ Expert ⏱ 35 min

Expression Trees & Dynamic LINQ

Represent executable logic as data with expression trees and build LINQ predicates dynamically at runtime.

Part 1: What You Will Learn

Represent executable logic as data with expression trees and build LINQ predicates dynamically at runtime.

  • Understand the difference between a delegate and `Expression<Func<...>>`.
  • Construct parameter, property, constant, and comparison expression nodes.
  • Combine nodes into a lambda expression.
  • Compile the expression for in-memory use or pass it to LINQ providers such as EF Core.

Project setup: Create a .NET 10 Console App and add `using System.Linq.Expressions;`.

Part 2: Topic-Specific Working Example

The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.

using System.Linq.Expressions;

public record Product(string Name, decimal Price);

static Expression<Func<Product, bool>>
    BuildMinimumPriceFilter(decimal minimumPrice)
{
    ParameterExpression product =
        Expression.Parameter(typeof(Product), "p");

    MemberExpression price =
        Expression.Property(product, nameof(Product.Price));

    ConstantExpression minimum =
        Expression.Constant(minimumPrice);

    BinaryExpression comparison =
        Expression.GreaterThanOrEqual(price, minimum);

    return Expression.Lambda<Func<Product, bool>>(
        comparison,
        product);
}

Product[] products =
[
    new("Mouse", 79.90m),
    new("Keyboard", 299.90m),
    new("Monitor", 899m)
];

Expression<Func<Product, bool>> filter =
    BuildMinimumPriceFilter(200m);

Func<Product, bool> compiled = filter.Compile();

foreach (Product product in products.Where(compiled))
    Console.WriteLine(product);

Part 3: How the Code Works

  • A normal `Func<Product,bool>` is executable code; an expression tree describes the structure of that code.
  • LINQ providers can inspect expression nodes and translate them—for example, EF Core can translate suitable expressions to SQL.
  • `Compile()` converts the expression tree into a delegate for in-memory execution.
  • Dynamic filters are useful when search conditions are chosen at runtime.

Part 4: Mini Project & Practice

Mini project: extend the filter builder so the user can optionally filter by minimum price and a product-name substring, combining conditions with `Expression.AndAlso`.

Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.

When you are comfortable with this lesson, continue to Lesson 34.

C# in Visual Studio 2026

📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition