using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
public class ConsoleAppForLambdas
private static readonly List<User> userData = UserDataSeed();
public static void Main(string[] args)
Console.WriteLine("Specify the property to filter");
string propertyName = Console.ReadLine();
Console.WriteLine("Value to search against: " + propertyName);
string value = Console.ReadLine();
var dn = GetDynamicQueryWithExpresionTrees(propertyName, value);
var output = userData.Where(dn).ToList();
foreach (var item in output)
Console.WriteLine("Filtered result:");
Console.WriteLine("\t ID: " + item.ID);
Console.WriteLine("\t First Name: " + item.FirstName);
Console.WriteLine("\t Last Name: " + item.LastName);
Console.WriteLine("==== DONE =====");
private static List<User> UserDataSeed()
new User{ ID = 1, FirstName = "Kevin", LastName = "Garnett"},
new User{ ID = 2, FirstName = "Stephen", LastName = "Curry"},
new User{ ID = 3, FirstName = "Kevin", LastName = "Durant"}
private static Func<User, bool> GetDynamicQueryWithFunc(string propName, object val)
Func<User, bool> exp = (t) => true;
exp = d => d.ID == Convert.ToInt32(val);
exp = f => f.FirstName == Convert.ToString(val);
exp = l => l.LastName == Convert.ToString(val);
private static Func<User, bool> GetDynamicQueryWithExpresionTrees(string propertyName, string val)
var param = Expression.Parameter(typeof(User), "x");
#region Convert to specific data type
MemberExpression member = Expression.Property(param, propertyName);
UnaryExpression valueExpression = GetValueExpression(propertyName, val, param);
Expression body = Expression.Equal(member, valueExpression);
var final = Expression.Lambda<Func<User, bool>>(body: body, parameters: param);
private static UnaryExpression GetValueExpression(string propertyName, string val, ParameterExpression param)
var member = Expression.Property(param, propertyName);
var propertyType = ((PropertyInfo)member.Member).PropertyType;
var converter = TypeDescriptor.GetConverter(propertyType);
if (!converter.CanConvertFrom(typeof(string)))
throw new NotSupportedException();
var propertyValue = converter.ConvertFromInvariantString(val);
var constant = Expression.Constant(propertyValue);
return Expression.Convert(constant, propertyType);
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }