C# 如何将代表作为<;T>;函数中的参数 公共委托布尔比较值(T1值1,T2值2); 公共静态bool compareTowolist(IEnumerable列表1、IEnumerable列表2、CompareValue CompareValue) { 返回list1.Select(item1=>list2.Any(item2=>compareValue(item1,item2)).All(search=>search) &&list2.Select(item2=>list1.Any(item1=>compareValue(item1,item2)).All(search=>search); }
在上述功能中;如何在调用“CompareTowolists”函数时将“compareValue”作为参数传递?使用与委托匹配的lambda表达式:C# 如何将代表作为<;T>;函数中的参数 公共委托布尔比较值(T1值1,T2值2); 公共静态bool compareTowolist(IEnumerable列表1、IEnumerable列表2、CompareValue CompareValue) { 返回list1.Select(item1=>list2.Any(item2=>compareValue(item1,item2)).All(search=>search) &&list2.Select(item2=>list1.Any(item1=>compareValue(item1,item2)).All(search=>search); },c#,linq,C#,Linq,在上述功能中;如何在调用“CompareTowolists”函数时将“compareValue”作为参数传递?使用与委托匹配的lambda表达式: public delegate bool CompareValue<in T1, in T2>(T1 val1, T2 val2); public static bool CompareTwoLists<T1, T2>(IEnumerable<T1> list1, IEnumerable<T2>
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);
}
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);
并将调用者方法更改为:
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比较值=
(u,r)=>r.激活
&&某物
&&u.SomethingElse!=r、 某些东西);
而不是使用代理;可以使用数组吗?如下所示'string[]Params=新字符串[]{“ProductCode”,“ProductName”};'@Pradu可以使用Func,而不是使用旧式委托。检查编辑后的答案。@Pradu另外,在第二种方法中,检查上面方法compareTowolists
的更新代码Select
是转换每个元素的投影,在您的案例中不需要它。是否可以将“Func compareValue”更改为列表表达式?我需要将列名列表传递给CompareList,而不是CompareValue。如果我仅通过ProductName,则仅比较ProductName。如果“列表表达式”有多个名称,则应与这些名称进行比较。可以使用任何绑定表达式吗?@Pradu上面的代码不限制您进行一个属性比较,您可以编写:Func compareValues=(u,r)=>u.Something==r.Something&&u.SomethingElse!=r、 某些东西(活动的)代码>。。因此,您可以基于0-N属性指定任何需要的比较。您可以使用Func
而不是定义自己的类型CompareValue
。
CompareValue<string, int> compareValues = SomeComparingMethod;
static bool SomeComparingMethod(string str, int number)
{
// code here
}
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);