Table of Contents

Linq is a great way to declaratively filter and query data in in a Type-Safe, Intuitive, and very expressive way. However, your users should not have to call you every time they have a new way to filter or query their data.

So here is a way for your users to filter their data no matter where that data comes from. Whether its Linq2SQL or an in-memory structure, now your users can have the power.

It is the most valuable feature that you can add for your users in 4 lines of code.I would also recommend actually reading the code. The entire project has only 233 lines of code in it - that's including the XAML.

The real functionality is in the two classes in the ViewModel. The UserControl is just a glorified DataTemplate for the ExpressionList.

I know that most of you will want to know how this bad boy works, so you can use the same techniques in your own solutions. However, you could just use the UserControl as-is by adding it straight into your XAML, and binding it to an ExpressionList, so that is what I will start with.

I first tried many other Dynamic Linq solutions. There is the "DynamicLinq" project explained in ScottGu's Blog which allows you to parse expressions in strings. So your users could write their own expressions in a text box which you could then apply to your Linq. I learned a lot about expressions from their implementation.

Then, there is the solution I almost used - The Dynamic Linq tool from the VB tool. It did almost exactly what I needed it to do, and you will notice that it looks a lot like the tool that I ended up creating which I am showing here today. The biggest problem is that it was written for WinForms and the functionality was too interwoven with the presentation. I actually needed one of the main benefits of MVVM (previously MVP) - The ability to persist the state even when the UI disappears and easily create default and saved sets of filters.

The CompleteExpression creates an input parameter out of the ObjectType and a lambda out of the first ExpressionVM. Then it loops through the rest of the ExpressionVMs appending the Expressions it gets from their MakeExpressions to the lambda based on their CombineOperator.

Comments and Discussions

Don't bother answering any of my other questions ... got it all figured out. I did end up adding the ability to search strings with 'StartsWith' or 'EndsWith'. Thought someone may find this helpful, so here is the code: