新建一个类库,然后添加一个”电脑“类 ,如下:
public class Computer
{ public Computer() { } public Computer(string brand,string model,double price,string color) { this.Brand = brand; this.Model = model; this.Price = price; this.Color = color; } public string Brand { get; set; } public string Model { get; set; } public double Price { get; set; } public string Color { get; set; }public string showinfo()
{ return string.Format("品牌:{0},型号:{1},价格:{2},颜色:{3}", Brand, Model, Price, Color); } }然后在新建一个控制台应用程序,添加下面的代码:
static void Main(string[] args)
{ List<Computer> list = GetComputer(); Console.WriteLine("请输入你要购买的电脑信息,如:品牌,型号,价格,颜色"); string query = Console.ReadLine(); List<Computer> listquery = new List<Computer>(); foreach (Computer item in list) { if(query==item.Brand) { listquery.Add(item); } else if(query==item.Model) { listquery.Add(item); } else if (query == Convert.ToString(item.Price)) { listquery.Add(item); } else if(query==item.Color) { listquery.Add(item); } } Console.WriteLine("符合您的要求的电脑如下"); foreach (Computer items in listquery) { Console.WriteLine(items.showinfo()); } Console.ReadKey(); }private static List<Computer> GetComputer()
{ List<Computer> listcom = new List<Computer>(); Computer comasus = new Computer("ASUS","Y系列",4230,"蓝色"); Computer comlenovo = new Computer("LENOVO", "E系列", 4230, "黑色"); Computer comlenovo1 = new Computer("LENOVO", "Y系列", 4250, "黄色"); Computer comacer = new Computer("ACER", "Y系列", 5000, "红色"); listcom.Add(comasus); listcom.Add(comlenovo); listcom.Add(comlenovo1); listcom.Add(comacer); return listcom; }