[C#基础训练]FoodRobot食品管理部分代码-2
参考代码:
using System;
using System.Collections.Generic;namespace FoodRobotDemo
{public class FoodInfo{ public string Name { get; set; } public int Id { get; set; } public int Count { get; set; }}public class FoodRobot{private List<FoodInfo> listFood;public FoodRobot(){listFood = new List<FoodInfo>();}public int this[string name,int id]{get{FoodInfo f = listFood.Find(x => x.Name ==name && x.Id == id);if (f != null){return f.Count;}else{Console.WriteLine("不存在 编号为{0}名称为{1}的食品",id,name);return -1;}}set{listFood.Add(new FoodInfo() { Name = name, Id = id, Count = value });}}//索引器重载,根据名字查找所有成绩public List<FoodInfo> this[string name]{get{List<FoodInfo> tempList = listFood.FindAll(x => x.Name == name);return tempList;}}}class Program{static void Main(string[] args){//多参数索引器和索引器重载 FoodRobot foodRobot = new FoodRobot();foodRobot["航天", 1] = 11;foodRobot["航空", 2] = 22;foodRobot["宇航", 3] = 33;foodRobot["宇航", 4] = 44; Console.WriteLine("编号:2 航空牌 食品数量:{0}",foodRobot["航空", 2]);Console.WriteLine(foodRobot["康师傅", 6]); List<FoodInfo> listFood = foodRobot["宇航"];if (listFood.Count > 0){foreach (var e in listFood){Console.WriteLine(string.Format("宇航 牌食品 编号:{0} 数量:{1}", e.Id, e.Count));}}else{Console.WriteLine("无该食品");}Console.ReadKey();}}
}