0

I have 3 variables:

String propertyName = "Title";
String propertyValue = "Bob";
Type propertyType = typeof(String);

How can I construct Expression <Func<T, bool>>, if T object has property Title?

I need Expression:

item => item.Title.Contains("Bob")

if propertyType is bool, then I need

item => item.OtherOproperty == false/true

and so on...

Oded
  • 489,969
  • 99
  • 883
  • 1,009
Lari13
  • 1,850
  • 10
  • 28
  • 55

1 Answers1

2

This code performs filtering and stores results in filtered array:

IQueryable<T> queryableData = (Items as IList<T>).AsQueryable<T>();

PropertyInfo propInfo = typeof(T).GetProperty("Title");
ParameterExpression pe = Expression.Parameter(typeof(T), "Title");
Expression left = Expression.Property(pe, propInfo);
Expression right = Expression.Constant("Bob", propInfo.PropertyType);
Expression predicateBody = Expression.Equal(left, right);

// Create an expression tree that represents the expression            
MethodCallExpression whereCallExpression = Expression.Call(
    typeof(Queryable),
    "Where",
    new Type[] { queryableData.ElementType },
    queryableData.Expression,
    Expression.Lambda<Func<T, bool>>(predicateBody, new ParameterExpression[] { pe }));

T[] filtered = queryableData.Provider.CreateQuery<T>(whereCallExpression).Cast<T>().ToArray();
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Tony Kh
  • 1,512
  • 11
  • 8
  • Thank you for answer. Can you please explain, how to define functions like 'Contains', 'StartsWith', 'EndsWith' here? – Lari13 Dec 27 '10 at 13:08
  • This link helped http://stackoverflow.com/questions/278684/how-do-i-create-an-expression-tree-to-represent-string-containsterm-in-c/278702#278702 – Lari13 Dec 27 '10 at 13:38
  • I would suggest to use another overload of Expression.Equal method and specify MethodInfo that performs desired equality check (not usual equality, but your custom - "LIKE" equality). But I am not sure. – Tony Kh Dec 27 '10 at 14:15