Comparing the expression <T>

Possible duplicate:
C #: checking for two expressions <Func <t, bool → → are the same

I have a bunch of Expression<Func<T, bool>> predicates, and I'd like to compare them for equality. Is there any way to do this?

Background. My library sorts items into "bins", controlled by whether the predicate returns true. If the caller wants to create a new box, I would like it to exist.

+6
expression-trees
source share
3 answers

You can use expr.ToString() as a start. Of course, this will not be too technically correct, since it will not take into account trees that differ in structure but are identical in function, and will not take into account named formal parameters for expressions. But he is close enough, and he is already there.

In general, the problem with different trees / identical functions can be so complex that you probably won't want to go there (you really need to build a compiler to say that two such expressions are identical).

+2
source share

EDIT: maybe this helps: ExpressionEqualityComparer from Linq-to-db4o . In a related question, we will discuss how to use it . Open source library.


You can follow the path of creating something like the universal DeepEquals method, which compares both internal (not sure if it is necessary) and external properties and fields, but it can be difficult, especially for getters properties with side effects, effects and Properties that do not implement IComparable or otherwise easily comparable objects.

Here's a possible way to do this, check out the PublicInstancePropertiesEqual method .

Keep in mind that what you mean with equality may not coincide with binary equality. It is enough to simply check the public properties (there are only eight of them) that can be placed in the extension method.

+1
source share

Perhaps matching Body , Parameters and ReturnType should be enough? At the very least, this should catch a situation where the same delegate is used to construct an expression.

If not, a deeper comparison may be helpful (look inside the Body ?).

However, comparing Expression (not Expression<T> s) seems complicated, I didn’t find Children there, and a big switch over the possible types of expressions would be evil.

0
source share

All Articles