Pradu
Pradu

Reputation: 61

How to pass delegates as <T> parameter in function

public delegate bool CompareValue<in T1, in T2>(T1 val1, T2 val2);
    public static bool CompareTwoLists<T1, T2>(IEnumerable<T1> list1, IEnumerable<T2> list2, CompareValue<T1, T2> compareValue)
    {
        return list1.Select(item1 => list2.Any(item2 => compareValue(item1, item2))).All(search => search)
                && list2.Select(item2 => list1.Any(item1 => compareValue(item1, item2))).All(search => search);
    }

In the above function; how to pass "compareValue" as parameter while calling "CompareTwoLists" function?

Upvotes: 2

Views: 105

Answers (2)

Zein Makki
Zein Makki

Reputation: 30032

You need to create a method (Normal or Anonymous) that matches that delegate's signature. Below is a sample:

var list1 = new List<string>();
var list2 = new List<int>();

CompareValue<string, int> compareValues = (x, y) => true;

CompareTwoLists(list1, list2, compareValues);

You can also replace the anonymous method, with a normal method:

CompareValue<string, int> compareValues = SomeComparingMethod;

static bool SomeComparingMethod(string str, int number)
{
    // code here
}

Another Approach

You can change your method to use Func:

public static bool CompareTwoLists<T1, T2>(IEnumerable<T1> list1, IEnumerable<T2> list2, 
                                           Func<T1, T2, bool> compareValue)
{
    return list1.All(x => list2.Any(y => compareValue(x, y)))
        && list2.All(x => list1.Any(y => compareValue(y, x)));
}

And Change the caller method to:

Func<User, Role, bool> compareValues = 
                            (u, r) => r.Active
                                   && u.Something == r.Something 
                                   && u.SomethingElse != r.SomethingElse);

Upvotes: 0

Richard Szalay
Richard Szalay

Reputation: 84754

With a lambda expression that matches the delegate:

var people = new List<Person>();
var orders = new List<Order>();

bool result = CompareTwoLists(people, orders, 
    (person, order) => person.Id == order.PersonId);

Or as a reference to a method that matches the delegate:

static bool PersonMatchesOrder(Person person, Order order)
{
    return person.Id == order.PersonId;
}

bool result = CompareTwoLists(people, orders, PersonMatchesOrder);

Upvotes: 1

Related Questions