[英]Creating a List<Book> c# console application
I want to create a List that holds a couple of books with the book title, authors name and year of publication. 我想创建一个List,其中包含几本书,书名,作者姓名和出版年份。 example: ( AuthorLastName, AuthorFirstName, “The book title”, year.)
例如:(AuthorLastName,AuthorFirstName,“书名”,年份。)
I know how to create List<int>
, for example: 我知道如何创建
List<int>
,例如:
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). 但问题是,如果我想创建一个书籍列表,我不能简单地创建一个
list<string>
或list<int>
因为我希望它包含字符串和int(如上例所示)。
So, Can anyone explain how I can make a List of books? 那么,任何人都可以解释我如何制作一本书籍清单吗?
You need to create a class
called Book
that contains the properties you want to have. 您需要创建一个名为
Book
的class
,其中包含您想要的属性。 Then you can instantiate a List<Book>
. 然后,您可以实例化
List<Book>
。
Example: 例:
public class Book
{
public string AuthorFirstName { get; set; }
public string AuthorLastName { get; set; }
public string Title { get; set; }
public int Year { get; set; }
}
And then, to use it: 然后,使用它:
var myBookList = new List<Book>();
myBookList.Add(new Book {
AuthorFirstName = "Some",
AuthorLastName = "Guy",
Title = "Read My Book",
Year = 2013
});
You need to define your class: 你需要定义你的类:
public class Book
{
public string Author { get; set; }
public string Title { get; set; }
public int Year { get; set; }
}
Then you can make a list of them: 然后你可以列出它们:
var listOfBooks = new List<Book>();
Do something like this 做这样的事情
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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.