如何在函数中将委托作为<t>参数传递

时间:2016-09-08 05:17:34

标签: c# linq

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);
    }

在上述功能中;如何在调用“CompareTwoLists”函数时将“compareValue”作为参数传递?

2 个答案:

答案 0 :(得分:1)

使用与委托匹配的lambda表达式:

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

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

或者作为与委托匹配的方法的引用:

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

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

答案 1 :(得分:0)

您需要创建一个与该委托签名匹配的方法(正常或匿名)。以下是一个示例:

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

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

CompareTwoLists(list1, list2, compareValues);

您还可以使用常规方法替换匿名方法:

CompareValue<string, int> compareValues = SomeComparingMethod;

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

另一种方法

您可以更改方法以使用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)));
}

并将调用者方法更改为:

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