Files
BooksConsolapp/Books.ConsoleApp/Program.cs
2019-11-24 23:14:41 +01:00

109 lines
3.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace Books.ConsoleApp
{
class Program
{
List<BooksByAuthor> BooksByAuthorCatalogue = null;
static void Main(string[] args)
{
IEnumerable<Book> books = BookSource.Read();
BooksByAuthorCatalogue = new List<BooksByAuthor>();
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<Book> { b };
var authorAndBooks = new BooksByAuthor(b.Author, newBookList);
BooksByAuthorCatalogue.Add(authorAndBooks);
}
private static void OutputBooksByAuthor()
{
foreach (var ba in BooksByAuthorCatalogue)
{
Console.Write("Author: {0, -28} Books: ", ba.Author);
foreach (var book in ba.Books)
{
Console.Write(book.title + ", ");
}
Console.Write(Environment.NewLine);
}
}
}
public class BooksByAuthor
{
public readonly string Author;
public readonly List<Book> Books;
public BooksByAuthor(string author, List<Book> books)
{
Author = author;
Books = books;
}
}
}