Development With A Dot

Blog on development in general, and specifically on .NET



My Friends

My Links

Permanent Posts

Portuguese Communities

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


ASP.NET MvcPager said:

Will there be some performance hit when using reflection?

# April 10, 2010 3:29 AM

Ricardo Peres said:

ASP.NET MvcPager:

You mean, if compared to the version in the System.Linq.Dynamic assembly? Yes, there is some (slight) performance penalty associated with the reflection process, but I'd say it's neglectable... See for yourself, create two loops, one for each version.

# April 10, 2010 12:17 PM