简体   繁体   中英

Pass lambda expression for Any() in Where() query as method parameter

I have the following theoretical method (Func param is probably not correct):

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. Also note, this is a quadratic time complexity, you might be better using Except that uses hashing with the appropriate ICompareable interface

Note 2 : This is quadratic time complexity, you might be better using Except that uses hashing with the appropriate ICompareable interface

Note 3 : If you want this done through EF, you will likely need to use an expression

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM