简体   繁体   中英

C#: How to add certain elements from another list in another class and print out?

I want to develop this option in a system that lists out all movies. The list genreList is created and declared private in another class and I am calling it in my main program.

part of the Movie Class:

public List<string> genreList = new List<string>();
public Movie() { }
public Movie(string tt, int dur, string cls, DateTime opendt, List<string> genrelist)
    {
        Title = tt;
        Duration = dur;
        Classification = cls;
        OpeningDate = opendt;
    }

    //methods
    public List<string> GetGenreList()
    {
        return genreList;
    }

And this is code in my main program:

List<Movie> MovieList = new List<Movie>();
        InitMovieList(MovieList);
if (option == 1)
            listAllMovies(MovieList);

static void getGenreList()
    {
        Movie moviegenre = new Movie();
        List<string> genreList = moviegenre.GetGenreList();

        genreList.Add("Action");
        genreList.Add("Adventure");
        genreList.Add("Comedy");
        genreList.Add("Fantasy");
        genreList.Add("Thriller");
    }

static void InitMovieList(List<Movie> MovieList)
    {
        Movie moviegenre = new Movie();
        List<string> genreList = moviegenre.GetGenreList();

        Movie m;

            m = new Movie("The Great Wall", 103, "NC16", Convert.ToDateTime("29-12-2016"), genreList);
            MovieList.Add(m);
        m = new Movie("Rogue One: A Star Wars Story", 134, "PG13", Convert.ToDateTime("15-12-2016"), genreList);
        MovieList.Add(m);
        m = new Movie("Office Christmas Party", 106, "M18", Convert.ToDateTime("15-01-2017"), genreList);
        m = new Movie("Power Rangers", 120, "G", Convert.ToDateTime("31-01-2017"), genreList);


    }

//list all movies
    static void listAllMovies(List<Movie> MovieList)
    {
        Movie moviegenre = new Movie();
        List<string> genreList = moviegenre.GetGenreList();
        Console.WriteLine();
        Console.WriteLine(string.Format("{0,-5}{1,-30}{2,-10}{3,-20}{4,-15}{5,-15}", "No","Title","Duration", "Genre", "Classification", "Opening Date"));

        for(int i = 0; i<MovieList.Count; i++)
        {
            Console.WriteLine(string.Format("{0,-5}{1,-30}{2,-10}{3,-20}{4,-15}{5,-15}", i + 1, MovieList[i].Title, MovieList[i].Duration, genreList[i], MovieList[i].Classification, MovieList[i].OpeningDate));

            Console.WriteLine();
            Console.Write("");
            Console.ReadLine();
        }
    }

My problem is that I am going to include certain elements like "Action, Adventure" or "Fantasy, Thriller" to one part of Movielist. The output should be something like this:

在此处输入图片说明

But what I have is this and a bundle of error messages: An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

And that prevented the program from continuing to the part I need.

在此处输入图片说明

Please advise me on what to do! Thank you very much.

You are misusing an index in listAllMovies . I've reformatted your code to make it easier to spot:

for(int i = 0; i<MovieList.Count; i++)
    {
        Console.WriteLine(
               string.Format(
                   "yourformatstring", 
                   i + 1, 
                   MovieList[i].Title, 
                   MovieList[i].Duration, 
                   genreList[i],     //  <----THE PROBLEM IS HERE
                   MovieList[i].Classification,         
                   MovieList[i].OpeningDate));

    }

You are using the same index i to get items from both your MovieList and your genreList . If your genrelist is shorter than your movielist, i will eventually become larger enough that it causes an ArgumentOutOfRangeException when you try to retrieve genreList[i] .


The solution to this isn't clear cut, because I don't quite understand how you are setting up the relationship between Movie and Genre. Nowhere in your code do you set up a direct relationship between a specific movie and the genres it belongs to.

  • You seem to pass a list of all genres into the Movie constructor. I would expect you to pass only the applicable genres
  • In your Movie constructor, you never do anything with the genrelist that you have passed to it.
  • While technically not causing a problem, you shouldn't store genreList inside each Movie class. It duplicates the same data for every Movie object; and I think it is indicative of a badly designed relationship between your movies and genres; which is the core of the issue you're faced with.

To still provide you with an answer, I'm going to assume that your Movie contains a List<Genre> Genres; where each Genre has a Name property.

This seems like what you want; even though it doesn't match with what you currently have.

for(int i = 0; i<MovieList.Count; i++)
    {
        Console.WriteLine(
               string.Format(
                   "yourformatstring", 
                   i + 1, 
                   MovieList[i].Title, 
                   MovieList[i].Duration, 
                   String.Join(",", MovieList[i].Genres.Select(x => x.Name).ToList()),     //  <----THE FIX IS HERE
                   MovieList[i].Classification,         
                   MovieList[i].OpeningDate));

    }

There is some problems in your code, firstly, in constructor of Movie , you should add line

this.genreList = genreList;

To add new movie to list:

Movie m = new Movie("The Great Wall", 103, "NC16", Convert.ToDateTime("29-12-2016"), new List<String>());
m.GetGenreList().Add("Action");
MovieList.Add(m);

And to print movie

for(int i = 0; i<MovieList.Count; i++)
{
      String genre = String.Join(",", MovieList[i].GetGenreList());
      Console.WriteLine(string.Format("{0,-5}{1,-30}{2,-10}{3,-20}{4,-15}{5,-15}", i + 1, MovieList[i].Title, MovieList[i].Duration, genre, MovieList[i].Classification, MovieList[i].OpeningDate));
      Console.WriteLine();
      Console.Write("");
      Console.ReadLine();
}

Then delete all these code:

Movie moviegenre = new Movie();
List<string> genreList = moviegenre.GetGenreList();

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM