Expressions Where

CSharp · Console

/Program.cs

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

public class Program
{
	public static void Main()
	{
		// find the Enumerable.Where with 2 parameters using reflection
		var where = typeof(Enumerable).GetMethods(BindingFlags.Public | BindingFlags.Static)
			.First(mi => mi.Name == "Where" && mi.GetParameters().Length == 2);

		// make generic Enumerable.Where<Item>
		var whereItem = where.MakeGenericMethod(typeof(Item));
		// sample data 
		IList<Item> items = new List<Item>
		{
			new Item
			{
				I = 1
			},
			new Item
			{
				I = 2
			}
		};
		// sample filter
		Func<Item, bool> filter = i => i.I > 1;
		// create expression
		var expr = Expression.Call(whereItem, Expression.Constant(items), Expression.Constant(filter));
		// validate
		var enumerable = Expression.Lambda<Func<IEnumerable<Item>>>(expr).Compile()();
		Console.WriteLine(enumerable.Count());
	}
}

public class Item
{
	public int I { get; set; }
}
;