linq where list contains any in list
Sounds like you want:
var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());
You can use a Contains
query for this:
var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));
If you use HashSet
instead of List
for listofGenres
you can do:
var genres = new HashSet<Genre>() { "action", "comedy" };
var movies = _db.Movies.Where(p => genres.Overlaps(p.Genres));
I guess this is also possible like this?
var movies = _db.Movies.TakeWhile(p => p.Genres.Any(x => listOfGenres.Contains(x));
Is "TakeWhile" worse than "Where" in sense of performance or clarity?
If the Genre
is an Entity and has its own Properties such as Title
, use the following code:
var listofGenresName = new List<string> { "action", "comedy" };
var movies = _db.Movies.Where(p => p.Genres.Any(x => listofGenresName.Any(g=> g == x.Title)));