MsnimROD
MsnimROD

Reputation: 43

C# How can I add objects to existing list of objects with user input

I have these objects from "book" class in a list (BLibShelf) but would like to start adding them to such list with console input

namespace Library
{
    class Program
    {
        static void Main(string[] args)
        {
            Book book1 = new Book("book one", "Author one", 900, 35, 16);
            Book book2 = new Book("book two", "Author two", 240, 42, 8);
            Book book3 = new Book("book three", "Author three", 700, 23, 8);
         
            List<Book> BLibShelf = new List<Book>();
            BLibShelf.AddRange(new List<Book>() { book1, book2, book3, book4, book5, book6, book7,  book8 });

 Console.ReadLine();

        }
       
    }

here is my book class

class Book
    {
        public string title;
        public string author;
        public int pages;
        public int Libcopies;
        public int BCopies;
                     
        public Book(string nTitle, string nAuthor, int nPages, int nLcopies, int nBcopies)
        {
            title = nTitle;
            author = nAuthor;
            pages = nPages;
            Libcopies = nLcopies;
            BCopies = nBcopies;
        }

        

Upvotes: 0

Views: 610

Answers (1)

cg-zhou
cg-zhou

Reputation: 563

I wrote a simple demo that supports inputting the new book title and pages.

You can implement the other fields yourself, hope it helps :)

    class Program
    {
        static void Main(string[] args)
        {
            Book book1 = new Book("book one", "Author one", 900, 35, 16);
            Book book2 = new Book("book two", "Author two", 240, 42, 8);
            Book book3 = new Book("book three", "Author three", 700, 23, 8);

            List<Book> BLibShelf = new List<Book>();
            BLibShelf.AddRange(new List<Book>() { book1, book2, book3 });

            Console.WriteLine("Total " + BLibShelf.Count + " books");

            Console.WriteLine("Please input the new book Title:");
            var title = Console.ReadLine();

            Console.WriteLine("Please input the new book Pages(integer):");
            var pages = int.Parse(Console.ReadLine());
            var newBook = new Book(title, string.Empty, pages, 0, 0);
            BLibShelf.Add(newBook);

            Console.WriteLine("Total " + BLibShelf.Count + " books");
            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
        }
    }

Upvotes: 1

Related Questions