C# linq 其中列表包含列表中的任何内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10667675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:45:02  来源:igfitidea点击:

linq where list contains any in list

c#linq

提问by Victor

Using linq, how can I retrieve a list of items where its list of attributes match another list?

使用 linq,如何检索其属性列表与另一个列表匹配的项目列表?

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);

采纳答案by Jon Skeet

Sounds like you want:

听起来你想要:

var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());

回答by BrokenGlass

You can use a Containsquery for this:

您可以Contains为此使用查询:

var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));

回答by Trevor

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?

在性能或清晰度方面,“TakeWhile”是否比“Where”差?

回答by Viacheslav Avsenev

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();

回答by Efraim Bart

If you use HashSetinstead of Listfor listofGenresyou can do:

如果您使用HashSet代替ListforlistofGenres您可以执行以下操作:

var genres = new HashSet<Genre>() { "action", "comedy" };   
var movies = _db.Movies.Where(p => genres.Overlaps(p.Genres));