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 I’ll say that I want to select from the list of films where it corresponds to 2 categories, for example, SQL statements:

SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'

I can get closer to linq like this:

var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);

But it acts like an OR request, not an AND. I want him to choose all the films in which there is a category of action and drama.

BTW: Movie.Categories is a list of strings . And Movie.Categories should contain elements in SelCat .

How to achieve this with Linq for objects?

+5
source share
7 answers
var q = from m in MovieList where SelCat.All(c => m.Categories.Contains(c))

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

, SelCat.

+9

, (.. SelCat movie.Categories), :

MovieList.Where(movie => !SelCat.Except(movie.Categories).Any()); 

, , :

MovieList.Where(movie => SelCat.Intersect(movie.Categories).Count() >= 2); 
+1
   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
+1
source

just do the intersection followed by the exception. it works, i wish i had to write it in vb.

Dim categories As New List(Of String)
Dim selected As New List(Of String)

        categories.Add("ali")
        categories.Add("ali2")
        categories.Add("ali3")
        categories.Add("ali4")

        selected.Add("ali2")
        selected.Add("ali4")


        Dim common = categories.Intersect(selected)

        If common.Except(selected).Count = 0 Then
            'true
        Else
            'false
        End If
0
source

A little collapsed:

var moviesInSelCat = MovieList.Where(m => SelCat.All(sc => m.Category.Any(c => c == sc)));
0
source
var result = from movie in movieList
             where selCat.All(selectedCategory => movie.Categories.Contains(selectedCategory))
             select movie;

remember the difference between .All()and.Any()

0
source

try it

var matches = MovieList.Where(m => SelCat.Except(
    m.Categories.Intersect(SelCat)).Count() == 0);
0
source

All Articles