I have a method that returns a list of lists of strings. It iterates through some objects to populate the list of strings. There is something wrong as it only repeatedly stores the first object. This is for an assignment. Any suggestions greatly appreciated
public List<List<string>> BookDetails()
{
List<List<string>> listOfBooks = new List<List<string>>();
List<string> bookDetails = new List<string>();
List<Book> b;
foreach (Library lib in libraryList)
{
b = lib.Booklist;
foreach (Book book in b)
{
bookDetails.Add(book.BookTitle);
bookDetails.Add(book.BookAuthor);
bookDetails.Add(lib.LibraryName);
bookDetails.Add(book.BookGenre);
listOfBooks.Add(bookDetails);
}
}
return listOfBooks;
}
You need a new book details object each time you add a book to the listOfBooks.
Move the creation of the book details object into the innermost loop, like so:
BTW, I had to wonder why you are adding the individual properties as strings to the listOfBooks instead of having something like a
List<Pair<String,Book>>, or even possiblyList<Pair<Library,Book>>.