Dynamic LINQ in an Assembly Near By

You may recall my post on Dynamic LINQ. I said then that you had to download Microsoft's samples and compile the DynamicQuery project (or just grab my copy), but there's another way. It turns out Microsoft included the Dynamic LINQ classes in the System.Web.Extensions assembly, not the one from ASP.NET 2.0, but the one that was included with ASP.NET 3.5! The only problem is that all types are private:

Here's how to use it:

Assembly asm = typeof(UpdatePanel).Assembly;
Type dynamicExpressionType = asm.GetType("System.Web.Query.Dynamic.DynamicExpression");
MethodInfo parseLambdaMethod = dynamicExpressionType.GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m => (m.Name == "ParseLambda") && (m.GetParameters().Length == 2)).Single().MakeGenericMethod(typeof(DateTime), typeof(Boolean));
Func<DateTime, Boolean> filterExpression = (parseLambdaMethod.Invoke(null, new Object [] { "Year == 2010", new Object [ 0 ] }) as Expression<Func<DateTime, Boolean>>).Compile();

List<DateTime> list = new List<DateTime> { new DateTime(2010, 1, 1), new DateTime(1999, 1, 12), new DateTime(1900, 10, 10), new DateTime(1900, 2, 20), new DateTime(2012, 5, 5), new DateTime(2012, 1, 20) };
IEnumerable<DateTime> filteredDates = list.Where(filterExpression);

Bookmark and Share

                             

2 Comments

Add a Comment

As it will appear on the website

Not displayed

Your website