[英]Pass lambda expression for Any() in Where() query as method parameter
我有以下理論方法(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));
...
...
}
是否有可能讓它相對容易地工作 - 即對該方法的實際調用並不復雜,以至於編寫和重復代碼一樣耗時。
如果是的話,當我調用該方法時如何傳遞“匹配”參數?
如果我明白你想要什么,你應該能夠做到這一點
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)));
}
用法
GenericMethod(list1,list2, (l1,l2) => l1.bob == l2.bob);
注意 1 :在這個簡單的示例中,是否可以節省大量代碼或看起來更令人滿意,這是值得商榷的。 另請注意,這是一個二次時間復雜度,您可能會更好地使用Except
使用帶有適當 ICompareable 接口的散列
注意 2 :這是二次時間復雜度,您可能會更好地使用Except
使用帶有適當 ICompareable 接口的散列
注意 3 :如果您希望通過 EF 完成此操作,您可能需要使用表達式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.