2

I want to create a List that holds a couple of books with the book title, authors name and year of publication. example: ( AuthorLastName, AuthorFirstName, “The book title”, year.)

I know how to create List<int>, for example:

class Program
{
    static void Main()
    {
    List<int> list = new List<int>();
    list.Add(10);
    list.Add(20);
    list.Add(25);
    list.Add(99);
    }
}

But the problem is, if I want to create a list of books, I can't simply make a list<string> or list<int> because I want it to contain strings and int's (as the example above).

So, Can anyone explain how I can make a List of books?

4

3 回答 3

6

您需要创建一个包含您想要拥有的属性的class调用。Book然后你可以实例化一个List<Book>.

例子:

public class Book
{
   public string AuthorFirstName { get; set; }
   public string AuthorLastName { get; set; }
   public string Title { get; set; }
   public int Year { get; set; }
}

然后,使用它:

var myBookList = new List<Book>();
myBookList.Add(new Book { 
                         AuthorFirstName = "Some", 
                         AuthorLastName = "Guy", 
                         Title = "Read My Book", 
                         Year = 2013 
                        });
于 2013-02-19T17:07:55.890 回答
3

你需要定义你的类:

    public class Book 
    {
       public string Author { get; set; }
       public string Title { get; set; }
       public int Year { get; set; }
    }

然后你可以列出它们:

var listOfBooks = new List<Book>();
于 2013-02-19T17:09:16.083 回答
2

做这样的事情

            public class Book
            {
                public string AuthorLastName { get; set; }
                public string AuthorFirstName{ get; set; }
                public string Title{ get; set; }
                public int Year { get; set; }
            }

            List<Book> lstBooks = new List<Book>();
            lstBooks.Add(new Book()
            {
                AuthorLastName = "What",
                AuthorFirstName = "Ever",
                Title = Whatever
                Year = 2012;
            });
于 2013-02-19T17:11:27.113 回答