Geeks With Blogs
.Nettuce Code Salad
public static class QueryableExtensions
    {
        public static IQueryable<T> Filter<T>(this IQueryable<T> queryable, IEnumerable<KeyValuePair<stringstring>> filters) where T : class
        {
            foreach (var filter in filters)
            {
                var propertyName = typeof(T).GetProperties().Select(x => x.Name).SingleOrDefault(x => x.ToLower() == filter.Key.ToLower());
                if (propertyName.IsNullOrWhiteSpace()) continue;
                var parameterExpression = Expression.Parameter(typeof(T));
                var propertyExpression = Expression.Property(parameterExpression, propertyName);
                var toStringCallExpression = Expression.Call(propertyExpression, typeof(T).GetMethod("ToString"));
                var toLowerCallExpression = Expression.Call(toStringCallExpression, typeof(string).GetMethod("ToLower"Type.EmptyTypes));
                var constantExpression = Expression.Constant(filter.Value.ToLower());
                var equalExpression = Expression.Equal(toLowerCallExpression, constantExpression);
                var methodCallExpression = Expression.Call(typeof(Queryable), "Where"new[] { typeof(T) }, queryable.Expression, Expression.Lambda<Func<T, bool>>(equalExpression, new[] { parameterExpression }));
                queryable = queryable.Provider.CreateQuery(methodCallExpression) as IQueryable<T>;
            }
            return queryable;
        }
    }
Posted on Tuesday, May 15, 2012 9:19 PM | Back to top


Comments on this post: IQueryable Dynamic Expressions

# re: IQueryable Dynamic Expressions
Requesting Gravatar...
Can you post a usage example of this?

TIA,
Dave
Left by Dave on May 16, 2012 7:08 AM

# re: IQueryable Dynamic Expressions
Requesting Gravatar...
an Example (I think)

var f = new Dictionary<string, string>()
f["FristName"] = "John";
f["LastName"] = "Smith"

var js = db.People.Filter(f);

would be the same as:

var js = from p in db.People
where p.FirstName == "John"
where p.LastName == "Smith"
select p;
Left by James Curran on May 16, 2012 3:44 PM

# re: IQueryable Dynamic Expressions
Requesting Gravatar...
This only provides Where() functionality. A version that supports a lot more LINQ is available here: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

For example: db.Where(...).OrderBy("orderdate");

Left by Travis on May 16, 2012 6:34 PM

# re: IQueryable Dynamic Expressions
Requesting Gravatar...
I now see the the light!

Thanks James!!

Dave
Left by Dave on Jun 12, 2012 7:11 AM

Your comment:
 (will show your gravatar)


Copyright © Jon Canning | Powered by: GeeksWithBlogs.net