Some Advice on Using Expression Trees.

mbb

Well-known member
Joined
Jun 3, 2009
Messages
52
Programming Experience
10+
I am considering writing some code that will allow a generic filter, or where part to be applied to a collection.

After a little research, it seems I will have to build an expression tree, compile it and pass the result into the where function of a collection etc.

The example I have simply defines one comparison, say x=10, then defines another comparison, say y=5 and then uses an and expression to join the two conditions together - x=10 and y =10.

My example stops there. But what if I wanted to and three, four or more conditions together?

Here's a snip of my code derived from the example to illustrate:

VB.NET:
        Dim character = Expression.Parameter(character, "character")

        Dim characterTypeExpression = Expression.Equal(Expression.Property(character, "CharacterTypeId"), Expression.Constant(pCharacterType))

        Dim regionExpression = Expression.Equal(Expressions.Expression.Property(character, "ResidencyId"), Expression.Constant(10))

        Dim andExpression = Expression.And(characterTypeExpression, regionExpression)
 
Are you saying that you just want to call Where on a collection to produce a filtered list of items, or are you saying that you want to be able to filter a list in situ?
 
Sorry. My intentions weren't very clear.

The the filter will be dynamic depending upon what a user selects in a UI or whether a filter is available at all, depending upon the screen the collection is being used in. So my code may look something like this:

VB.NET:
if isActiveFilterA and isSelectedFilterA then
  Add FilterA to Expression Tree
end if

if isActiveFilterB and isSelectedFilterB then
 Add FilterB to Expression Tree
end if

...

if isActiveFilterZ and isSelectedFilterZ then
 Add FilterZ to Expression Tree
end if

Of course in my example an imcrementing value (A, B ... Z) suggests a collection and looping.

The example from my book (similar to my first post) didn't really go on to discuss more than two conditions in the where clause, and I'm not really finding anything on the Web. Even though there are plenty of examples of walking an expression tree, nothing much about building one.

I know I could use recursion to keep ANDing expressions together, but that seems very clumsy. Do I have it correctly, or have I missed something?
 
Back
Top