Possible Duplicate:
C#: Checking if two Expression<Func<T, bool>> are the same
I've got a bunch of Expression<Func<T, bool>>
predicates and I'd like 开发者_StackOverflowto compare them for equality. Is there any way to do that?
Background: My library sorts items into "bins", governed by whether the predicate returns true. If a caller wants to create a new bin, I'd like to see if the bin already exists.
You can use expr.ToString()
as a start. Of course this is not going to be too technically correct, since it won't take into account trees that differ in structure but are identical in function and it will also not take into account differently named formal parameters for the expressions. But it's close enough, and it's already there.
In general, the different trees/identical function problem can be so hard that you probably don't wont to go there (you would in effect need to build a compiler to be able to tell that two such expressions are identical).
EDIT: maybe this helps: the ExpressionEqualityComparer
from Linq-to-db4o. In a related question, there's some discussion about how to use this. The library is open source.
You could go down the road of creating something like a generic DeepEquals
method, which compares both internal (not sure this is necessary) and external properties and fields, but this can be tricky, especially for property getters with side-effects and properties that don't implement IComparable
or are otherwise easily comparable objects.
Here's a possible way of doing that, check the method PublicInstancePropertiesEqual.
Keep in mind that what you mean with equality, might not be the same as binary equality. It might be enough just to check the public properties (there are only eight of them), which you can place in an extension method.
Perhaps comparing the Body
, Parameters
and ReturnType
should be enough? At least, this should catch the situation where the same delegate is used to construct the expression.
If not, more deep comparison (look inside Body
?) might be helpful.
However, comparing Expression
s (not Expression<T>
s) seem to be not easy, I didn't find the Children there, and having a big switch over the possible expression types would be evil.
精彩评论