1

I have something like this:

class Movie
{
    public string Title;
    public List<string> Genres = new List<string>();
}


static void Main(string[] args)
{
    List<string> genreList = new List<string();
        genreList.Add("Crime");
        genreList.Add("Thriller");
    var movies = new List<Movie>();
    movies.Add(new Movie { Title = "Pulp Fiction", Genres = genreList });

    genre.List.Clear();
    genrelist.Add("Adventure");
    genrelist.Add("Sci-Fi");
    movies.Add(new Movie { Title = "Back to the Future" Genres = genreList });

    genre.List.Clear();
    genrelist.Add("Adventure");
    genrelist.Add("Crime");
    genrelist.Add("Sci-Fi");
    movies.Add(new Movie { Title = "The Dark Knight", Genres = genreList });
}

How can I query the movies List to get a list of all of the genres within the Genres variables? I want the output to be: Adventure Crime Sci-Fi Thriller

Thanks as always!

1
  • 3
    genreList.Clear will infact clear the entries in the previous movie.Genres as well.
    – Chandu
    Jul 13, 2011 at 0:48

1 Answer 1

3
using System.Linq;

movies.SelectMany(m => m.Genres).Distinct();

Also, note Cybernate's comment about all the movies having the same list. Try initializing like,

movies.Add(new Movie { 
   Title = "Pulp Fiction",
   Genres = { "Crime", "Thriller" } // calls Add on existing List
});
// or
// assign a copy of genreList
genreList.Clear();
genrelist.Add("Adventure");
genrelist.Add("Sci-Fi");
movies.Add(new Movie { Title = "Back to the Future", Genres = genreList.ToList() });
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.