Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Expression<T> [duplicate]

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 to 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.

like image 745
Roger Lipscombe Avatar asked Mar 23 '11 13:03

Roger Lipscombe


2 Answers

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).

like image 61
Jon Avatar answered Nov 05 '22 18:11

Jon


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.

like image 28
Abel Avatar answered Nov 05 '22 19:11

Abel