使用linq,如何检索其属性列表与另一个列表匹配的项目列表?
以这个简单的例子和伪代码:
List<Genres> listofGenres = new List<Genre>() { "action", "comedy" });
var movies = _db.Movies.Where(p => p.Genres.Any() in listofGenres);
答案 0 :(得分:183)
听起来像你想要的那样:
var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());
答案 1 :(得分:58)
您可以使用Contains
查询:
var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));
答案 2 :(得分:4)
如果您将HashSet
使用List
代替listofGenres
,则可以执行以下操作:
var genres = new HashSet<Genre>() { "action", "comedy" };
var movies = _db.Movies.Where(p => genres.Overlaps(p.Genres));
答案 3 :(得分:2)
我想这也有可能吗?
var movies = _db.Movies.TakeWhile(p => p.Genres.Any(x => listOfGenres.Contains(x));
“TakeWhile”在性能或清晰度方面是否比“Where”更差?
答案 4 :(得分:1)
或者像这样
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();