P
P
Pavel2018-02-27 17:44:17
C++ / C#
Pavel, 2018-02-27 17:44:17

How to compare two lambda expressions?

Essence of a question: there are two identical events. How to compare them so that the AreEqual method would return True.

Action a = () => Debug.Log(true); 
Action b = () => Debug.Log(true);

var result = AreEqual(a, b);

Once compared through a method that took one lambda as a template, and then compared them. The signature is something like this.
public bool AreEqual<T>(T template, object action)
{

}

Plus, you need it to work in this form:
var result = AreEqual(()=> Debug.Log(true), b);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Kuznetsov, 2018-02-28
@DarkRaven

In theory, you can unwind this expression into some kind of string, according to your rule. That is, to translate this expression, as LINQ is translated into the corresponding SQL (with reservations and saving information on types) - if it's rude.
But, I would not recommend doing this in principle, because. These are all costs and the profit is not obvious.

C
Csus4, 2018-02-28
@Csus4

Db4objects is available in nuget

using System;
using System.Diagnostics;
using System.Linq.Expressions;

using Db4objects.Db4o.Linq.Expressions;

class Test
{

    static void Main()
    {
        Expression<Action> a = () => Debug.Write(1);
        Expression<Action> b = () => Debug.Write(1);
        Expression<Action> c = () => Debug.Write(2);
        Expression<Action> d = () => a.Compile();

        Func<Expression, Expression, bool> eq =
            ExpressionEqualityComparer.Instance.Equals;

        Console.WriteLine(eq(a, b));                                          //true
        Console.WriteLine(eq(a, c));                                          //false
        Console.WriteLine(eq(a, d));                                          //false 
        Console.WriteLine(eq(a, (Expression<Action>)(() => Debug.Write(1)))); //true
        Console.ReadKey();
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question