Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to objects List in list

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?

like image 330
Rick Rat Avatar asked Nov 30 '10 08:11

Rick Rat


2 Answers

var q = from m in MovieList where SelCat.All(c => m.Categories.Contains(c))

Quite close to what you would say describing the problem in English:

Select movies where the movie categories contain all the categories in SelCat.

like image 149
Jon Avatar answered Oct 01 '22 21:10

Jon


   var SelectedCategories = List<string>();//list of selected categories

from movie in MovieList
join selCat in Categories.Where(SelectedCategories.Contains(selCat.Category)
on movie.category equals selCat.category
select movie
like image 32
hazimdikenli Avatar answered Oct 01 '22 19:10

hazimdikenli