using System; using System.Collections.Generic; using System.Globalization; namespace Books.ConsoleApp { class Program { List BooksByAuthorCatalogue = null; static void Main(string[] args) { Book[] books = BookSource.Read(); BooksByAuthorCatalogue = new List(); for (int i = 0; i < books.Length; i++) { var book = books[i]; if (AuthorIsAlreadyCataloged(book.author)) { // there are some(1 or more) books by this author already found and catalogued var authorCatalogueIndex = LocateAuthorAlreadyCataloged(book.author); var existingBooks = BooksByAuthorCatalogue[authorCatalogIndex].Books; existingBooks.Add(book); } else { CatalogueNewAuthor(book); } } } private static bool AuthorIsAlreadyCataloged(string author) { var authorAlreadyCatalogued = false; // we'll iterate over the catalogue to find the author - if athors's already been cataloged for (int j = 0; j < BooksByAuthorCatalogue.Count; j++) { var entry = BooksByAuthorCatalogue[j]; if (entry.author == author) { authorAlreadyCatalogued = true; break; } } return authorAlreadyCatalogued; } private static int LocateAuthorAlreadyCataloged(string author) { var authorCatalogIndex = 0; // We'll iterate over the cataloge to find the author's index for (int j = 0; j < BooksByAuthorCatalogue.Count; j++) { var entry = BooksByAuthorCatalogue[j]; if (entry.Author == author) { authorCatalogIndex = j; break; } } } private static void CatalogueNewAuthor(Book b) { // there are NONE books by this author already found and cataloged var newBookList = new List {b}; var authorAndBooks = new BooksByAuthor(b.Author, newBookList); BooksByAuthorCatalogue.Add(authorAndBooks); } private static void OutputBooksByAuthor() { for (int i = 0; i < BooksByAuthorCatalogue.Count; i++) { BooksByAuthor ba = BooksByAuthorCatalogue[i]; Console.Write("Author: {0, -28} Books: ", ba.Author); for (int j = 0; j < ba.Books.Count; j++) { Console.Write(ba.Books[j].title + ", "); } Console.Write(Environment.NewLine); } } } public class BooksByAuthor { public readonly string Author; public readonly List Books; public BooksByAuthor(string author, List books) { Author = author; Books = books; } } }