Linq to 对象列表中的列表
我有一个电影列表
List<Movie> MovieList
和一个选定类别的列表
List<string> SelCat
假设我想从电影列表中选择与 2 个类别匹配的位置,如下面的 SQL 语句:
SELECT * FROM MovieList WHERE MovieList.Category = 'Action ' AND MovieList.Category = 'Drama'
我可以像这样使用 linq 有点接近:
var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p )) select b);
但它的作用类似于 OR 查询,而不是 AND。我希望它选择所有具有动作和戏剧类别的电影。
顺便说一句:Movie.Categories 是一个字符串列表。并且Movie.Categories 必须包含SelCat 中的项目。
如何使用 Linq to Objects 实现此目的?
I have a list of movies
List<Movie> MovieList
and I have a list of selected categories
List<string> SelCat
And say I want to select from the movie list where it matches 2 categories, like the SQL statement below:
SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'
I can get kinda close with linq like so:
var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);
But it acts like an OR query, not an AND. I want it to select all movies that have a category of action and drama.
BTW: Movie.Categories is a List of string. AND Movie.Categories must contain items in the SelCat.
How do I achieve this with Linq to Objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
非常接近您用英语描述问题的内容:
选择电影类别包含
SelCat
中的所有类别的电影。Quite close to what you would say describing the problem in English:
Select movies where the movie categories contain all the categories in
SelCat
.如果您希望电影匹配所有的有趣类别(即
SelCat
中的所有类别都存在于movie.Categories
中),您可以这样做:另一方面,如果您希望电影与至少 2 个所选类别相匹配:
If you want the movie to match all of the interesting categories (i.e. all of the categories in
SelCat
are present inmovie.Categories
), you can do:On the other hand, if you want the movie to match atleast 2 of the selected categories:
请记住
.All()
和.Any()
之间的区别remember the difference between
.All()
and.Any()
有点复杂:
A bit convoluted:
试试这个
try this
只需先进行相交,然后进行例外即可。
它有效,很抱歉我必须用 VB 编写它。
just do an intersect followed by except.
it works, im sorry i had to write it in vb.