使用 linq,如何检索其属性列表与另一个列表匹配的项目列表?
以这个简单的例子和伪代码为例:
List<Genres> listofGenres = new List<Genre>() { "action", "comedy" });
var movies = _db.Movies.Where(p => p.Genres.Any() in listofGenres);
听起来像你想要的:
var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());
您可以为此使用Contains
查询:
var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));
如果你使用HashSet
而不是List
forlistofGenres
你可以这样做:
var genres = new HashSet<Genre>() { "action", "comedy" };
var movies = _db.Movies.Where(p => genres.Overlaps(p.Genres));
我想这也是可能的吗?
var movies = _db.Movies.TakeWhile(p => p.Genres.Any(x => listOfGenres.Contains(x));
在性能或清晰度方面,“TakeWhile”是否比“Where”差?
如果Genre
是一个实体并且有它自己的属性,比如Title
,使用下面的代码:
var listofGenresName = new List<string> { "action", "comedy" };
var movies = _db.Movies.Where(p => p.Genres.Any(x => listofGenresName.Any(g=> g == x.Title)));
或者像这样
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();