linq where list contains any in list
C#LinqC# Problem Overview
Using linq, how can I retrieve a list of items where its list of attributes match another list?
Take this simple example and pseudo code:
List<Genres> listofGenres = new List<Genre>() { "action", "comedy" });
var movies = _db.Movies.Where(p => p.Genres.Any() in listofGenres);
C# Solutions
Solution 1 - C#
Sounds like you want:
var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());
Solution 2 - C#
You can use a Contains
query for this:
var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));
Solution 3 - C#
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));
Solution 4 - C#
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?
Solution 5 - C#
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)));
Solution 6 - C#
Or like this
class Movie
{
public string FilmName { get; set; }
public string Genre { get; set; }
}
...
var listofGenres = new List<string> { "action", "comedy" };
var Movies = new List<Movie> {new Movie {Genre="action", FilmName="Film1"},
new Movie {Genre="comedy", FilmName="Film2"},
new Movie {Genre="comedy", FilmName="Film3"},
new Movie {Genre="tragedy", FilmName="Film4"}};
var movies = Movies.Join(listofGenres, x => x.Genre, y => y, (x, y) => x).ToList();