如何在C#命令行程序中阻止列表出现重复名称的条目?
C#命令行产品管理程序去重方案
方案一:添加条目时阻止重复名称输入
直接在创建新Item前检查当前产品分类下是否已存在同名条目,从源头避免重复:
// 用户输入完成后先执行重复检查 string inputName = "用户输入的产品名称"; string inputDesc = "用户输入的产品描述"; int inputStock = 用户输入的库存数量; string currentProductType = "当前选中的产品类型"; bool hasDuplicate = false; if (Products.ContainsKey(currentProductType)) { // 忽略大小写判断,如需严格匹配可去掉StringComparison参数 hasDuplicate = Products[currentProductType].Any(item => item.Name.Equals(inputName, StringComparison.OrdinalIgnoreCase)); } if (hasDuplicate) { Console.WriteLine("该名称的产品已存在,无法重复添加"); } else { // 正常创建并添加条目 List<Item> itemList; if (!Products.ContainsKey(currentProductType)) { ProductTypeList.Add(currentProductType); itemList = new List<Item>(); Products.Add(currentProductType, itemList); } else { itemList = Products[currentProductType]; } itemList.Add(new Item(inputName, inputDesc, inputStock)); } // 修正原Item类的字段拼写不一致问题,统一命名规范 public class Item { public string Name; public string Description; public int Availability; public Item(string name, string description, int availability) { Name = name; Description = description; Availability = availability; } public void Display() { // 原展示逻辑 } }
方案二:展示时仅显示单个同名条目
如果不需要拦截添加,仅在展示时去重,直接在遍历前对currentItemList做处理即可,不改动原有foreach结构:
case 1: // 查看产品 Console.Clear(); // 按名称去重,保留第一个出现的条目(需.NET Core 3.0+/NET 5+支持) var uniqueItems = currentItemList.OrderBy(x => x.Name) .DistinctBy(x => x.Name) .ToList(); foreach (var item in uniqueItems) { item.Display(); } break;
进阶:展示时合并同名条目的库存
若希望同一名称的条目合并库存数量,而非仅保留第一个,可通过分组求和实现:
case 1: // 查看产品 Console.Clear(); var mergedItems = currentItemList.GroupBy(x => x.Name) .Select(g => new Item( g.Key, g.First().Description, // 取第一个条目的描述 g.Sum(item => item.Availability) // 合并所有同名条目的库存 )) .OrderBy(x => x.Name) .ToList(); foreach (var item in mergedItems) { item.Display(); } break;
内容的提问来源于stack exchange,提问作者dangoqut132
相关产品推荐
相关产品推荐

