Dynamic LINQ Extension Method

Remember those old posts on Dynamic LINQ? You are probably aware that Microsoft has made its implementation available as a Nuget package, but, like I said, you already have it in your machine, hidden inside the System.Web.Extensions assembly.

In order to make it easier to use, I wrote a simple extension method that works with plain old IQueryable<T>. And here it is:

   1: public static IQueryable<T> Where<T>(this IQueryable<T> query, String restriction, params Object[] values)
   2: {
   3:     Assembly asm = typeof(UpdatePanel).Assembly;
   4:     Type dynamicExpressionType = asm.GetType("System.Web.Query.Dynamic.DynamicExpression");
   5:     MethodInfo parseLambdaMethod = dynamicExpressionType.GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m => (m.Name == "ParseLambda") && (m.GetParameters().Length == 2)).Single().MakeGenericMethod(typeof(T), typeof(Boolean));
   6:     Expression<Func<T, Boolean>> expression = parseLambdaMethod.Invoke(null, new Object[] { restriction, values }) as Expression<Func<T, Boolean>>;
   7:  
   8:     return (query.Where(expression));
   9: }

It even supports parameters! Just two simple examples – I am using Entity Framework, but you can use whatever you like, this is totally generic:

   1: //without parameters
   2: var productsWithPriceGreaterThan100 = ctx.Products.Where("Price > 100").ToList();
   3:  
   4: //with parameters
   5: var productsWithPriceLowerThan100 = ctx.Products.Where("Price < @0", 100).ToList();

To make it clear, all parameters must be indicated as @0, @1, and so on. It is better to use them, because the database engine can reuse the execution plan.

There’s one limitation, though: you can’t compare each value on its own, you have to specify one of its properties. For example, you can’t have:

   1: var productNames = ctx.Products.Select(x => x.Name).Where("@it != @0", "Some Name").ToList();

The @it parameter is not recognized, which is a pity.

Make sure you have references to both System.Web and System.Web.Extensions, this is required, and won’t affect anything.

As always, glad to be of service! Winking smile

                             

1 Comment

Add a Comment

As it will appear on the website

Not displayed

Your website