我是新手,目前正在学习C#,我必须编写一个控制台应用程序,在这个应用程序中,用户输入一个列表,比如说,书籍,但是它是一个类列表。假设我有一门课叫“读书”。
class Books
{
public string name;
public string description;
public double price;现在我创建了一个具有Books类型的列表
List<Books> myBooks = new List<Books>();我要求用户添加这些书:
for (int x = 0; x <= s; x++)
{
Books newbook = new Books();
Console.WriteLine("\nPlease input the name, description and price of the book:\n");
newbook.name = Console.ReadLine();
newbook.description = Console.ReadLine();
newbook.price = Convert.ToDouble(Console.ReadLine());
myBooks.Add(newbook);
//Displaying what the user just entered
Console.WriteLine("{0} - {1}: {2}. Price: {3}", /*add index*/, newbook.name, newbook.description, newbook.price);
}正如你所看到的,我需要一些东西来显示书在列表中的哪一部分,对于每一本书(书籍)。
我尝试使用,myBooks.Count()和myBooks[x],但是它们要么返回相同的值(因为列表的大小),要么只返回[namespace.class]。是否有一个不涉及添加另一个类或创建另一个变量的解决方案(在整数形式中,它也可以是基于零的)?
提前谢谢。
发布于 2018-01-25 15:22:23
要获取最近添加的项的索引,可以使用(myBooks.Count() - 1)。
或者,您可以在添加项目之前存储从myBooks.Count()返回的值,该值将是添加该项的索引。
最后,在测试示例中,您还可以使用x的值。
发布于 2018-01-25 15:28:53
如果您想要索引集合,只需使用数组:
int totalBooks = 25;
Books[] myBooks = new Books[totalBooks]; // 25 is the number of books an the indexes are from 0 to 24
for (int i = 0; i < totalBooks; i++)
{
Books newbook = new Books();
Console.WriteLine("\nPlease input the name, description and price of the book {0} :\n", (i+1));
newbook.name = Console.ReadLine();
newbook.description = Console.ReadLine();
newbook.price = Convert.ToDouble(Console.ReadLine());
myBooks[i] = newbook;
//Displaying what the user just entered
Console.WriteLine("{0} - {1}: {2}. Price: {3}", (i+1), newbook.name, newbook.description, newbook.price);
}发布于 2018-01-25 16:24:19
您将在列表中使用IndexOf方法
myBooks.Add(newbook);
//Displaying what the user just entered
Console.WriteLine("{0} - {1}: {2}. Price: {3}", myBooks.IndexOf(newbook),
newbook.name, newbook.description, newbook.price);我不明白为什么myBooks.Count()也不能工作,因为您正在列表的末尾插入,但是最具描述性的方法是使用IndexOf。
附带注意:您的类Books描述了一本书;一般实践是以单数对象命名类。为了简单或清晰,您可能需要将其重命名为Book。
https://stackoverflow.com/questions/48446253
复制相似问题