Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq where list contains any in list

Tags:

c#

linq

People also ask

Can I check if a list contains any item from another list C#?

You could use a nested Any() for this check which is available on any Enumerable : bool hasMatch = myStrings. Any(x => parameters. Any(y => y.

Where with Contains in Linq?

LINQ Contains operator is used to check whether an element is available in sequence (collection) or not. Contains operator comes under Quantifier Operators category in LINQ Query Operators. Below is the syntax of Contains operator.

How use any in Linq C#?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

How do you check if a list is a subset of another list C#?

You can simply check to see that the set difference between query2 and query1 is the empty set: var isSubset = ! query2. Except(query1).


Sounds like you want:

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

You can use a Contains query for this:

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

If you use HashSet instead of List for listofGenres you can do:

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

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?


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

If the Genre is an Entity and has its own Properties such as Title, use the following code:

var listofGenresName = new List<string> { "action", "comedy" };
var movies = _db.Movies.Where(p => p.Genres.Any(x => listofGenresName.Any(g=> g == x.Title)));