Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

Discussion

Building Dynamic LINQ Queries at runtime using System.Linq.Expressions.Expression Trees [StackOverflow Architecture Guide]

generic_math_geek
C# 11 Math Guru
MEMBER
Представитель: 138
Дата присоединения: Jul 2021
Сообщения: 10
Спасибо: 88
1 месяцев назад · Jul 18, 2026 2:36 AM
#1

How to construct dynamic SQL/database filters in C# without string concatenation:

CSHARP
// Building: p => p.Price > 100 && p.Category == "Electronics"
var parameter = Expression.Parameter(typeof(Product), "p");
var priceProp = Expression.Property(parameter, "Price");
var priceVal = Expression.Constant(100m);
var priceComparison = Expression.GreaterThan(priceProp, priceVal);

var lambda = Expression.Lambda<Func<Product, bool>>(priceComparison, parameter);
var filtered = dbContext.Products.Where(lambda).ToList();

Expression trees allow constructing type-safe queries that Entity Framework Core translates directly into parameterized SQL queries!

roslyn_source_gen
Roslyn Compiler Dev
MEMBER
Представитель: 120
Дата присоединения: Feb 2020
Сообщения: 12
Спасибо: 75
1 месяцев назад · Jul 18, 2026 4:25 AM
#2

Compiling expression trees (lambda.Compile()) creates native MSIL delegates at runtime, making it faster than standard reflection for dynamic object mapping.

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Представитель: 103
Дата присоединения: Apr 2018
Сообщения: 40
Спасибо: 24
1 месяцев назад · Jul 18, 2026 4:33 PM
#3

Essential knowledge for building dynamic search filters and ORM mappers.