all posts

Where list x has an item in it like y

Published to Blog on 12 Nov 2009

A list of movies walks into a bar… forget it, that’s not going to work. There once was a list of movies named Gurty Blanchez… hmm, that’s not going to work either.

This is another one of those “posting it more for me than you” posts.

Whoever is responsible for assigning the genres for movies - the production houses, distributors, retailers, whoever – likes to get creative and do things like “Indie Action Thriller”, “Arthaus Crime Drama”, etc.

I have this list of movies. Movies can have multiple genres assigned to them like blogs posts can have multiple tags. I model Genres as a property of my Movie class as a list of strings: simple stuff. I want to filter movies by genre but I only want to use the “main” genres for filtering: Comedy, Drama, Thriller, Family, Action, Fantasy, etc.

I added the filtering code a while back and everything seemed to be working fine. But recently I found a bug where when filtering movies it was only returning movies that had a genre that was an exact match to the filter, “Comedy” for example, and was missing movies that had genres like “British Comedy”.

I looked at my code and found:

return filteredMovies = movies
    .Where(x => x.Genres != null)
    .Where(x => x.Genres.Contains(selectedGenre))
    .ToList();

Naive mistake. The above code can be translated as: “given a list of movies give me any movie that has a genre in its list of genres that is the same as the filter you selected”.

What I really wanted was: “given a list of movies give me any movie that has a genre in its list of genres where the filter you selected is included in all or part of the genre’s name”. Seems like a small thing but it makes a huge difference in the end result. The code should look like this instead:

return filteredMovies = movies
    .Where(x => x.Genres != null)
    .Where(x => x.Genres.Exists(g => g.Contains(selectedGenre)))
    .ToList();

I love Linq.


Dan Hounshell
Web geek, nerd, amateur maker. Likes: apis, node, motorcycles, sports, chickens, watches, food, Nashville, Savannah, Cincinnati and family.
Dan Hounshell on Twitter