c# - 我想在 C# 中使用对象数组显示一些产品
问题描述
我有一堂课
public class Product
{
private long id;
private String name;
private String internCode;
private String producer;//
public long Id { get => id; set => id = value; }
public string Name { get => name; set => name = value; }
public string InternCode { get => internCode; set => internCode = value; }
public string Producer { get => producer; set => producer = value; }
public void display()
{
Console.WriteLine("Products: " +Id+" "+Name + "[" +InternCode + "] " + Producer);
}
}
这是程序类
public static void Main(string[] args)
{
Product prod1 = new Product();
Product prod2 = new Product();
Console.WriteLine("The Id for the first product is:");
prod1.Id = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The name of the first product is:");
prod1.Name = Console.ReadLine();
Console.WriteLine("The Intern Code is:");
prod1.InternCode = Console.ReadLine();
Console.WriteLine("The producer is:");
prod1.Producer = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("The Id for the second product is:");
prod2.Id = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The name for the second product is:");
prod2.Name = Console.ReadLine();
while (prod2.Name == prod1.Name)
{
Console.WriteLine("This product has already been introduced. Please introduce a new product:");
prod2.Name = Console.ReadLine();
}
Console.WriteLine("The intern code is:");
prod2.InternCode = Console.ReadLine();
Console.WriteLine("The producer is:");
prod2.Producer = Console.ReadLine();
Console.WriteLine("The products are:");
Console.WriteLine();
prod1.display();
Console.WriteLine();
prod2.display();
Console.WriteLine();
Console.ReadKey();
}
我想通过用户输入读取产品并使用对象数组 Product[] array1=new Product[] 显示它们,而不是使用 prod1 和 prod2 对象。请给我任何示例或任何链接来记录我如何解决这个问题。谢谢!
解决方案
我建议您使用 List,因为您有 Add 方法来添加新产品。要检查产品是否存在,您可以使用 Linq 的 IEnumerable 的 Any 扩展:
var products = new List<Product>();
...
while (!lastuserinput.Equals("exit"))
{
var productName = Console.ReadLine();
if (products.Any(product=>product.Name.Equals(productName))
{
Console.WriteLine("product already exists");
continue;
}
...
productList.Add(new Product
{
...
Name = productName,
...
};
...
}
推荐阅读
- excel - How to count the nth consecutive instance of a word in a list in excel?
- python-3.x - since i switched to python 3, my flask page stopped displaying ASCII characters correctly
- java - Groovy read json-file, add new key : value and write back (Jenkins)
- python - Counting objects in specific positions on an image
- java - 如何使用 Angular + Spring + JSON 自定义登录/身份验证
- python - Passing a string to .loc accessor pandas
- shell - Specify desktop in which application should open from shell script
- vue.js - VSCode Syntax Highlighting not working with Vue / Vetur
- mysql - 备份 MySQL 数据库
- python - Docker setup for two apps