using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Globalization; namespace Books.Console { class Program { List BooksByAuthorCatalogue = null; static void Main(string[] args) { IEnumerable books = BookSource.Read(); BooksByAuthorCatalogue = new List(); foreach (var book in books) { 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 foreach (var entry in BooksByAuthorCatalogue) { 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() { foreach (var ba in BooksByAuthorCatalogue) { System.Console.Write("Author: {0, -28} Books: ", ba.Author); foreach (var book in ba.Books) { System.Console.Write(book.title + ", "); } System.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; } } }