using System.Collections.Generic;
using System.Linq.Expressions;
using System.Diagnostics;
public int Id { get; set; }
public string Name { get; set; }
public static Func<TEntity, bool> GetComparer<TEntity, TProperty>(Expression<Func<TEntity, TProperty>> selector, TProperty value)
var propertyRef = selector.Body;
var parameter = selector.Parameters[0];
var constantRef = Expression.Constant(value);
var comparer = Expression.Lambda<Func<TEntity, bool>>
(Expression.Equal(propertyRef, constantRef), parameter)
public static ICollection<A> CreateData()
var list = new List<A>();
for (int i = 0; i < 100000; i++)
Name = rand.Next(2) == 1 ? "A" : "B"
public static void Main()
var sw = new Stopwatch();
var compsw = new Stopwatch();
int[] counts = new int[3];
foreach (var a in list.Where(x => x.Name == "A"))
Console.WriteLine("Using LINQ with known parameter (Base line): {0}ms", sw.ElapsedMilliseconds);
var comp = GetComparer((A x) => x.Name, "A");
foreach (var a in list.Where(comp))
Console.WriteLine("Using compiled expression: {0}ms, compilation time: {1}ms", sw.ElapsedMilliseconds, compsw.ElapsedMilliseconds);
foreach (var a in list.Where(x => x.GetType().GetProperty("Name").GetValue(x).ToString() == "A"))
Console.WriteLine("Using reflection: {0}ms", sw.ElapsedMilliseconds);
if (counts[0] != counts[1] || counts[0] != counts[2] || counts[1] != counts[2])
Console.WriteLine("there was an error in test {0} {1} {2}", counts[0], counts[1], counts[2]);
Console.WriteLine("{0} {1} {2}", counts[0], counts[1], counts[2]);