Queryable has two methods for where both take two parameters, so I'm not even sure which one is correct.
You need one that gets Expression<Func<T, bool>> predicate .
Here's how you can dynamically build a predicate similar to (T item) => item.Property == value :
public static partial class QueryableExtensions { public static IQueryable<T> WhereEquals<T>(this IQueryable<T> source, string member, object value) { var item = Expression.Parameter(typeof(T), "item"); var memberValue = member.Split('.').Aggregate((Expression)item, Expression.PropertyOrField); var memberType = memberValue.Type; if (value != null && value.GetType() != memberType) value = Convert.ChangeType(value, memberType); var condition = Expression.Equal(memberValue, Expression.Constant(value, memberType)); var predicate = Expression.Lambda<Func<T, bool>>(condition, item); return source.Where(predicate); } }
I tried to write it in such a way that you can step over the code to understand what it does. The only line that may be required to explain:
var memberValue = member.Split('.').Aggregate((Expression)item, Expression.PropertyOrField);
This is an easy way to handle nested properties like obj.Prop1.Prop2 , etc. If you do not need such features, you can simply use this:
var memberValue = Expression.PropertyOrField(item, member);
source share