Building a Dynamic Predicate Based on Conditions
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; class Product { public string Name { get; set; } public int Price { get; set; } } class Program { static void Main() { var products = new List<Product> { new Product { Name = "Laptop", Price = 1000 }, new Product { Name = "Phone", Price = 700 }, new Product { Name = "Tablet", Price = 400 } }; string propertyToCheck = "Price"; int minPrice = 500; var parameter = Expression.Parameter(typeof(Product), "p"); var property = Expression.Property(parameter, propertyToCheck); var constant = Expression.Constant(minPrice); var condition = Expression.GreaterThan(property, constant); var lambda = Expression.Lambda<Func<Product, bool>>(condition, parameter); var filteredProducts = products.AsQueryable().Where(lambda).ToList(); foreach (var product in filteredProducts) { Console.WriteLine($"{product.Name}, ${product.Price}"); } } }