Reputation: 1641
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;
}
Upvotes: 2
Views: 1971
Reputation: 64026
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:
foreach (Book book in b)
{
List<string> bookDetails = new List<string>(); //<-- move this line
bookDetails.Add(book.BookTitle);
bookDetails.Add(book.BookAuthor);
bookDetails.Add(lib.LibraryName);
bookDetails.Add(book.BookGenre);
listOfBooks.Add(bookDetails);
}
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 possibly List<Pair<Library,Book>>
.
Upvotes: 2