C# Lists Book Repository


This entry is part 3 of 5 in the series C# Lists

In the previous post we used a list of strings. In this post we are going to create a class of Books and create a list of books. This example leads into another post we have at this site on lambda expressions called C# Lambda Part 2. Here we are going to tie in lists from the previous post and set up our class that will be used in the lambda post. Mosh Hamedani also uses this Book Repository in his video on LINQ. Before studying LINQ you should be familiar with extension methods.

The first thing we do here is create a class of Book. It is very simple. Next we need to create another class called Book Repository.

namespace ListOfBooksRepository
{
    class Book
    {
        public string Title { get; set; }
        public int Price { get; set; }
    }
}

Next we can create another class that stores a list of books.

    class BookRepository
    {
        public List<Book> GetBooks()
        {
            return new List<Book>
                {
                    new Book() { Title ="bk 1", Price = 5},
                    new Book() { Title = "bk 2", Price = 6 },
                    new Book() { Title = "bk 3", Price = 17 }
                };
        }
    }

Here is our Main

using System;
namespace ListOfBooksRepository
{
    class Program
    {
        static void Main(string[] args)
        {
             var books = new BookRepository().GetBooks();
             foreach (var book in books)
             {
                 Console.WriteLine(book.Title);
             }
        }
    }
}

Series Navigation<< C# Lists String RepositoryC# Lists of Class Objects >>