我正在做一个简单的股票系统。这是我在库存中添加商品的方法。
如何添加选项以按文章的code
搜索某篇文章以查找相应文章的名称?
这些是我的清单:
public static List<string> item = new List<string>();
public static List<string> code = new List<string>();
public static List<string> price = new List<string>();
public static List<string> unit = new List<string>();
添加项目的方法:
public static void addItem()
{
Console.Clear();
Console.Write("\nNumber of items to add: ");
count = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert the items:");
for (int i = 1; i <= count; i++)
{
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Item[" + i + "]: ");
item.Add(Console.ReadLine());
Console.Write("Code[" + i + "]: ");
code.Add(Console.ReadLine());
Console.Write("Price[" + i + "]: ");
price.Add(Console.ReadLine());
Console.Write("Unit[" + i + "]: ");
unit.Add(Console.ReadLine());
}
}
搜索项目的方法:
public static void searchItem()
{
Console.WriteLine("Type the code to search an article");
string code2 = Console.ReadLine();
for (int i = 0;; i++)
{
if (code.Contains(code2))
{
Console.WriteLine("The item are: " + item[i]);
}
}
}
答案 0 :(得分:1)
执行Diligent Key Presser建议的内容 - 引入一个描述单个项目的专用类 - 而不是:
public static List<string> item = new List<string>();
public static List<string> code = new List<string>();
public static List<string> price = new List<string>();
public static List<string> unit = new List<string>();
有这个:
public class MyClass
{
public string Item {get;set;}
public string Code {get;set;}
public string Price {get;set;}
public string Unit {get;set;}
}
public static List<MyClass> item = new List<MyClass>();
将addItem()
更改为:
public static void addItem()
{
Console.Clear();
Console.Write("\nNumber of items to add: ");
count = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert the items:");
for (int i = 0; i < count; i++) //note use of zero-based array
{
item.Add(new MyClass());
Console.WriteLine("\nitem[" + i + "]: ");
Console.Write("item[" + i + "].Item: ");
item[i].Item = Console.ReadLine();
Console.Write("item[" + i + "].Code: ");
item[i].Code = Console.ReadLine();
Console.Write("item[" + i + "].Price: ");
item[i].Price = Console.ReadLine());
Console.Write("item[" + i + "].Unit: ");
item[i].Unit = Console.ReadLine();
}
}
将searchItem()
更改为:
public static void searchItem()
{
Console.WriteLine("Type the code to search an article");
string code = Console.ReadLine();
for (int i = 0; i < item.Count; i++)
{
if (item[i].Code == code)
{
Console.WriteLine("The item's Item is: " + item[i].Item);
Console.WriteLine("The item's Code is: " + item[i].Code);
Console.WriteLine("The item's Price is: " + item[i].Price);
Console.WriteLine("The item's Unit is: " + item[i].Unit);
}
}
}