Skip to content

Instantly share code, notes, and snippets.

@jrgcubano
Created October 28, 2014 12:41
Show Gist options
  • Save jrgcubano/2ad25efbbfc0a41a66e1 to your computer and use it in GitHub Desktop.
Save jrgcubano/2ad25efbbfc0a41a66e1 to your computer and use it in GitHub Desktop.
Simple example to filter a collection using properties with dot notation.
public class Sport
{
public string Name {get; set;}
public string League {get; set;}
}
public class Person
{
public string Name {get; set;}
public Sport Sport {get; set;}
}
public class Company
{
public List<Person> Workers {get; set;}
}
void Main()
{
var company = new Company();
List<Person> workers = new List<Person>();
workers.Add(new Person() { Name = "Marco", Sport = new Sport() { Name = "Futbol", League = "MLS" }});
workers.Add(new Person() { Name = "Juan", Sport = new Sport() { Name = "Futbol", League = "MLS" }});
workers.Add(new Person() { Name = "Jordan", Sport = new Sport() { Name = "Futbol", League = "MLT" }});
workers.Add(new Person() { Name = "Jorge", Sport = new Sport() { Name = "Baskeball", League = "NBA" }});
string propertyName = "Sport.Name";
string propertyLeague = "Sport.League";
string method = "Contains";
ParameterExpression param = Expression.Parameter(typeof(Person), "x");
var firstExp = GetExpression<Person>(param, propertyName, "Fut", method);
var secondExp = GetExpression<Person>(param, propertyLeague, "MLS", method);
var allWithOrExp = Expression.OrElse(firstExp, secondExp);
var firstLamda = GetLamda<Person>(param, firstExp);
var allWithOrLamda = GetLamda<Person>(param, allWithOrExp);
var sportsFirst = workers.AsQueryable().Where(firstLamda);
var sportsWithOr = workers.AsQueryable().Where(allWithOrLamda);
sportsFirst.Dump();
sportsWithOr.Dump();
}
public static Expression GetExpression<T>(ParameterExpression param, string property, object constant, string method)
{
Type sourceType = typeof(T);
Type type = sourceType;
string[] props = property.Split('.');
ParameterExpression parameterExpression = param;
Expression expr = parameterExpression;
foreach(string prop in props)
{
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
ConstantExpression contExp = Expression.Constant(constant);
MethodInfo methodInfo = typeof(string).GetMethod(method, new[] { typeof(string) });
var exp = Expression.Call(expr, methodInfo, contExp);
return exp;
}
public static Expression<Func<T, bool>> GetLamda<T>(ParameterExpression param, Expression exp)
{
Type sourceType = typeof(T);
Type delegateType = typeof(Func<,>).MakeGenericType(sourceType, typeof(bool));
var lambdaExp = Expression.Lambda(delegateType, exp, param);
var typedExpression = (Expression<Func<T, bool>>)lambdaExp;
return typedExpression;
}
// Define other methods and classes here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment