Project: Linq.Dynamic.Expression


Create dynamic LINQ expression:
void Main()
{
	var anonymous = new { Name = "Bill", Age = 3 };
	var anonymousList = new [] { anonymous }.Dump();	
	anonymousList.DynamicClause("Bill", 2).Dump();
	
	var customer = new Customer { Name = anonymous.Name, Age = anonymous.Age };
	var customerList = new [] { customer }.Dump();	
	customerList.DynamicClause("Bill", 2).Dump();
}

public class Customer
{
	public string Name { get; set; }
	
	public int Age { get; set; }
}

public static class AnonymousExtensions
{
	public static IEnumerable<T> DynamicClause<T>(this IEnumerable<T> source, string name, int age)
	{
		return
			source.Where(DynamicFunction<T>(name, age));
	}
			
	private static Func<T, bool> DynamicFunction<T>(string name, int age)
	{
		var parameter = Expression.Parameter(typeof(T), "obj");
		
		// Name == name
		var namePropertyExpression = Expression.Property(parameter, "Name");	
		var nameExpression = Expression.Equal(namePropertyExpression, Expression.Constant(name));
		
		// Age > age
		var agePropertyExpression = Expression.Property(parameter, "Age");
		var ageExpression = Expression.GreaterThan(agePropertyExpression, Expression.Constant(age));
	
		var expression = Expression.AndAlso(nameExpression, ageExpression);

		// obj => obj.Name == name && obj.Age > age
		var lamda = Expression.Lambda<Func<T, bool>>(expression, parameter);
		
		return
			lamda.Compile();
	}
}

Last edited Apr 2, 2012 at 1:18 PM by teoarch, version 1

Comments

No comments yet.