using System.Collections.Generic;
using System.Linq.Expressions;
public static class DynWhere
public static Expression<Func<T, bool>> CreatePredicate<T>(List<string> propsToSearch, string valueToSearch)
var parameter = Expression.Parameter(typeof(T), "record");
if (!propsToSearch.Any() || string.IsNullOrEmpty(valueToSearch))
return Expression.Lambda<Func<T, bool>>(Expression.Constant(true), parameter);
var props = typeof(T).GetProperties()
.Intersect(propsToSearch.Distinct());
var containsMethod = typeof(string).GetMethod("Contains");
.Select(p => Expression.PropertyOrField(parameter, p))
.Aggregate((Expression)Expression.Constant(false),
(c, n) => Expression.OrElse(c,
Expression.Call(n, containsMethod, Expression.Constant(valueToSearch)))
var lambda = Expression.Lambda<Func<T, bool>>(body, parameter);
internal class MyDBObject
Prop1 = Prop2 = Prop3 = Prop4 = Prop5 =
Prop11 = Prop12 = Prop13 = Prop14 = Prop15 =
Prop21 = Prop22 = Prop23 = Prop24 = Prop25 =
public int Id { get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public string Prop4 { get; set; }
public string Prop5 { get; set; }
public string Prop11 { get; set; }
public string Prop12 { get; set; }
public string Prop13 { get; set; }
public string Prop14 { get; set; }
public string Prop15 { get; set; }
public string Prop21 { get; set; }
public string Prop22 { get; set; }
public string Prop23 { get; set; }
public string Prop24 { get; set; }
public string Prop25 { get; set; }
public static void Main()
List<MyDBObject> dbRecords = new List<MyDBObject>
new MyDBObject { Id = 1, Prop2 = "O1_P2", Prop3 = "O1_P3", Prop12 = "O1_P12", Prop15 = "O1_P15", Prop24 = "O1_P24", Prop25 = "O1_P25" },
new MyDBObject { Id = 2, Prop15 = "O2_P15", Prop21 = "test", Prop22 = "O2_P22", Prop23 = "O2_P23", Prop24 = "O2_P24", Prop25 = "O2_P25" },
new MyDBObject { Id = 3, Prop21 = "O3_P21", Prop22 = "O3_P22", Prop23 = "O3_P23", Prop24 = "test", Prop25 = "O3_P25" }
var lambda = CreatePredicate<MyDBObject>(new[] { "Prop21", "Prop5" }.ToList(), "test");
var query = dbRecords.AsQueryable().Where(lambda).ToArray();
foreach (var rs in query)
Console.WriteLine("Id: " + rs.Id);