How to test expressions equality [duplicate]
Asked Answered
D

2

1

Possible Duplicate:
Most efficient way to test equality of lambda expressions
How to check if two Expression<Func<T, bool>> are the same

How to test that two expressions are the same like this sample

        string firstname = "Ahmed";
        Expression<Func<string, bool>> exp1 = (s) => s.Contains(firstname);
        Expression<Func<string, bool>> exp2 = (s) => s.Contains(firstname);

        Console.WriteLine(exp1 == exp2);//print false as two references are no equal

now how to ensure that expression1 equals to expression2 , as they have the same criteria?

Dislodge answered 1/9, 2012 at 16:11 Comment(0)
Y
1

Here is the code for ExpressionEqualityComparer which can show how to do it.

https://source.db4o.com/db4o/trunk/db4o.net/Db4objects.Db4o.Linq/Db4objects.Db4o.Linq/Expressions/

Yet answered 1/9, 2012 at 16:12 Comment(0)
B
4

If you want to check if the expressions are equal, not just that they always evaluate the same way, you can do this:

exp1.ToString() == exp2.ToString()

Note that even insignificant changes will cause this to return false, like making it j => j.Contains(firstname) or using exp2 from this class:

public class Test
{
    static string firstname;
    public static Expression<Func<string, bool>> exp2 = s => s.Contains(firstname);
}

(even though the lambdas look the same in the code, the ToStrings show that one is using Test.firstname and the other is using a compiler-generated class's firstname)

Still, this might be useful depending on where your expressions come from.

Border answered 1/9, 2012 at 17:4 Comment(0)
Y
1

Here is the code for ExpressionEqualityComparer which can show how to do it.

https://source.db4o.com/db4o/trunk/db4o.net/Db4objects.Db4o.Linq/Db4objects.Db4o.Linq/Expressions/

Yet answered 1/9, 2012 at 16:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.