[英]Pass lambda expression for Any() in Where() query as method parameter
I have the following theoretical method (Func param is probably not correct):我有以下理论方法(Func 参数可能不正确):
private void GenericMethod<T>(List<T> list1, List<T> list2, Func<T, bool> match) where T : class
{
//I'm trying to avoid repeating this nearly identical functionality
//For different lists types
//var items = list1.Where(e => !list2.Any(f => f.SomeId == e.SomeId));
//where match is f.SomeId == e.SomeId
var items = list1.Where(e => list2.Any(match));
...
...
}
Is it possible to get this to work with relative ease - ie the actual call to the method is not so complex that it's as time consuming to write as it is to just repeat the code.是否有可能让它相对容易地工作 - 即对该方法的实际调用并不复杂,以至于编写和重复代码一样耗时。
and if yes how do I pass in the "match" parameter when I call the method?如果是的话,当我调用该方法时如何传递“匹配”参数?
If I understand what you want, you should be able to do this如果我明白你想要什么,你应该能够做到这一点
private void GenericMethod<T>(List<T> list1, List<T> list2, Func<T, T, bool> match)
{
var items = list1.Where(e => !list2.Any(f => match(f,e)));
}
Usage用法
GenericMethod(list1,list2, (l1,l2) => l1.bob == l2.bob);
Note 1 : In this simple example it's debatable if it's saving you much code or will look that much more satisfying.注意 1 :在这个简单的示例中,是否可以节省大量代码或看起来更令人满意,这是值得商榷的。 Also note, this is a quadratic time complexity, you might be better using Except
that uses hashing with the appropriate ICompareable interface另请注意,这是一个二次时间复杂度,您可能会更好地使用Except
使用带有适当 ICompareable 接口的散列
Note 2 : This is quadratic time complexity, you might be better using Except
that uses hashing with the appropriate ICompareable interface注意 2 :这是二次时间复杂度,您可能会更好地使用Except
使用带有适当 ICompareable 接口的散列
Note 3 : If you want this done through EF, you will likely need to use an expression注意 3 :如果您希望通过 EF 完成此操作,您可能需要使用表达式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.