For a certain project I’m working on I needed a way to filter data in a LINQ query (LINQ to Entities) based on input given by the user. The user has to be able to select a certain property and compare that to given values.

The property names are fetched from the entity class using reflexion and listed in a dropdown input control. The next step would be to somehow use the selected value in my LINQ query as a property name. That however didn’t seem to be so trivial at first .. until I discovered expression trees.

Expression trees allow you to build expressions in the same way that you can use Lambda to build expressions but on a more verbose/dynamic way. It allows you to continue where lambda expressions can’t go thus giving you much more power.

The lambda expression num => num < 5 can be rewritten using expression trees as

In order to access the property/field from a given object (considering we would get an object as input in the first place), we can use the Expression.Property or Expression.Field methods, depending on what you want to access. In my case that would be a property.

 

The first argument you need to pass is the object you want to access. Mostly that would be a ParameterExpression. The second argument is the name of the field as a string. Exactly what we need.

If we add all these components together we can create a nice class that allows us to easily create filters:

We can now easily create filters:

And we can simply add this filter to our LINQ query using .Where(filter) . It’s as simply as that. In any case the filter class isn’t perfect yet, the type conversion code can definitely be tweaked. But it does provide me with a solid base to continue on!