C#中如何按食谱名称查询并展示对应食材信息?
解决C#食谱管理的两个核心问题
问题根源
你当前用多个独立的List(比如ingredientNames、ingredientQuantities)分散存储食谱数据,没有把单个食谱的所有信息(名称、食材、步骤)关联起来,导致新食谱的食材会覆盖旧食谱的索引位置,所以只能获取最后一条食谱的信息。
解决方案:面向对象重构数据结构
通过创建封装类,把单个食谱的所有信息打包成对象,再用一个列表存储所有食谱,就能轻松关联和访问任意食谱的信息。
1. 定义实体类
// 封装单份食材的所有属性 public class Ingredient { public string Name { get; set; } public double Quantity { get; set; } public string Unit { get; set; } public int Calories { get; set; } public string FoodGroup { get; set; } } // 封装单个食谱的所有信息 public class Recipe { public string Name { get; set; } public List<Ingredient> Ingredients { get; set; } = new List<Ingredient>(); public List<string> Steps { get; set; } = new List<string>(); // 自动计算总卡路里 public int TotalCalories => Ingredients.Sum(i => i.Calories); }
2. 重构RecipeDetails方法
修改后该方法负责创建单个食谱对象并添加到全局列表:
// 全局存储所有食谱的列表 private List<Recipe> _allRecipes = new List<Recipe>(); public void RecipeDetails() { var newRecipe = new Recipe(); Console.WriteLine("Enter Name of recipe : "); newRecipe.Name = Console.ReadLine(); Console.WriteLine("Enter Number of ingredients : "); if (!int.TryParse(Console.ReadLine(), out int maxIngredients)) { Console.WriteLine("Invalid number, defaulting to 1 ingredient."); maxIngredients = 1; } // 收集食材 for (int ingredientCount = 0; ingredientCount < maxIngredients; ingredientCount++) { var ingredient = new Ingredient(); Console.WriteLine($"Enter name of ingredient {ingredientCount + 1}:"); ingredient.Name = Console.ReadLine(); // 循环直到输入有效数量 while (true) { Console.WriteLine($"Enter quantity of {ingredient.Name} : 1, 2, 4, 6, 8, 10 :"); if (double.TryParse(Console.ReadLine(), out double quantity)) { ingredient.Quantity = quantity; break; } Console.WriteLine("Enter Numeric values only !"); } Console.WriteLine($"Enter unit of measurement for {ingredient.Name}: Single, Bunch, Tsp, Cup "); ingredient.Unit = Console.ReadLine(); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("- A calorie is a unit of energy commonly used to measure the amount of energy in food and the energy expended through physical activity -"); Console.ForegroundColor = ConsoleColor.White; // 循环直到输入有效卡路里值 while (true) { Console.WriteLine($"Enter amount of calories for {ingredient.Name}: "); if (int.TryParse(Console.ReadLine(), out int calories)) { ingredient.Calories = calories; break; } Console.WriteLine("Enter Numeric values only !"); } Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("- A food group is a category of foods that share similar nutritional properties -"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"Enter the food group {ingredient.Name} belongs to. (Fruit, Vegetables, Grains, Protein or Dairy) : "); ingredient.FoodGroup = Console.ReadLine(); newRecipe.Ingredients.Add(ingredient); } // 收集步骤 Console.WriteLine("Enter number of steps : "); if (!int.TryParse(Console.ReadLine(), out int steps)) { Console.WriteLine("Invalid number, defaulting to 1 step."); steps = 1; } for (int s = 0; s < steps; s++) { Console.WriteLine($"Enter description of step {s + 1}"); string description = Console.ReadLine(); newRecipe.Steps.Add(description); } // 将新食谱添加到全局列表 _allRecipes.Add(newRecipe); }
1. 如何展示从列表获取的用户输入?
编写方法根据食谱名称查找并输出对应信息:
public void DisplayRecipe(string recipeName) { // 忽略大小写查找食谱 var recipe = _allRecipes.FirstOrDefault(r => string.Equals(r.Name, recipeName, StringComparison.OrdinalIgnoreCase)); if (recipe == null) { Console.WriteLine($"Recipe '{recipeName}' not found."); return; } Console.WriteLine($"\n=== {recipe.Name} ==="); Console.WriteLine($"Total Calories: {recipe.TotalCalories}"); Console.WriteLine("\nIngredients:"); foreach (var ingredient in recipe.Ingredients) { Console.WriteLine($"- {ingredient.Quantity} {ingredient.Unit} of {ingredient.Name} ({ingredient.Calories} calories, {ingredient.FoodGroup})"); } Console.WriteLine("\nSteps:"); for (int i = 0; i < recipe.Steps.Count; i++) { Console.WriteLine($"{i + 1}. {recipe.Steps[i]}"); } } // 调用示例:提示用户输入要查看的食谱名称 public void PromptDisplayRecipe() { Console.WriteLine("\nEnter the name of the recipe you want to view:"); string name = Console.ReadLine(); DisplayRecipe(name); }
2. 如何访问循环添加到列表中的项?
所有食谱存储在_allRecipes列表中,可通过以下方式访问:
- 通过索引访问(比如获取第一个食谱):
if (_allRecipes.Count > 0) { Recipe firstRecipe = _allRecipes[0]; Console.WriteLine($"First recipe: {firstRecipe.Name}"); }
- 遍历所有食谱:
Console.WriteLine("\nAll Recipes:"); foreach (var recipe in _allRecipes) { Console.WriteLine($"- {recipe.Name} ({recipe.Ingredients.Count} ingredients, {recipe.Steps.Count} steps)"); }
- 条件筛选访问(比如找出卡路里超过500的食谱):
var highCalorieRecipes = _allRecipes.Where(r => r.TotalCalories > 500).ToList(); Console.WriteLine($"\nHigh calorie recipes ({highCalorieRecipes.Count}):"); foreach (var recipe in highCalorieRecipes) { Console.WriteLine($"- {recipe.Name}: {recipe.TotalCalories} calories"); }
内容的提问来源于stack exchange,提问作者Avient_711
相关产品推荐
相关产品推荐

