如何在C#中利用Dictionary实现通过Code查询Product详情?
问题描述
现有C#密封类Product定义如下:
public sealed class Product { public int Id { get; set; } public string Name { get; set; } public double Amount{ get; set; } }
目前使用Dictionary<int, Product>存储产品数据:
private static readonly Dictionary<int, Product> Products = new Dictionary<int, Product>() { { 1001, new Product{ Id = 1001, Name = "Product 1", Amount = 50.00 } }, { 1002, new Product{ Id = 1002, Name = "Product 2", Amount = 30.00 } }, ... }
现在需要为Product新增Code字段,该字段可包含多个值,数据示例如下:
| ID | Name | Code | Amount |
|---|---|---|---|
| 1001 | Product 1 | A1001, B1001 | 50.00 |
| 1002 | Product 2 | A1002 | 30.00 |
| 1003 | Product 3 | A1003, B1003 | 100.00 |
曾尝试创建以ID为键的单独Codes字典:
private static readonly Dictionary<int, int[]> Codes = new Dictionary<int, int[]>() { { 1001, new int[] { A1001, B1001 } }, ... }
需求是通过Code直接查询对应的产品详情,请问如何利用Dictionary实现这一功能?
解决方案
步骤1:更新Product类
先把Code字段加到Product中,因为一个产品对应多个Code,推荐用HashSet<string>(自动去重)或List<string>:
public sealed class Product { public int Id { get; set; } public string Name { get; set; } public double Amount { get; set; } // 用HashSet避免单个产品出现重复Code,无需去重则换List<string> public HashSet<string> Codes { get; set; } = new HashSet<string>(); }
步骤2:构建Code到Product的反向映射字典
要实现Code快速查产品,核心是创建以Code为键、Product为值的Dictionary。如果存在一个Code对应多个产品的场景,就用Dictionary<string, List<Product>>,下面以单Code对应单产品为例:
静态数据场景:初始化时构建映射
如果产品数据是静态的,可在初始化主字典后同步生成映射:
// 产品主字典 private static readonly Dictionary<int, Product> Products = new Dictionary<int, Product>() { { 1001, new Product{ Id = 1001, Name = "Product 1", Amount = 50.00, Codes = {"A1001", "B1001"} } }, { 1002, new Product{ Id = 1002, Name = "Product 2", Amount = 30.00, Codes = {"A1002"} } }, { 1003, new Product{ Id = 1003, Name = "Product 3", Amount = 100.00, Codes = {"A1003", "B1003"} } } }; // Code到Product的映射字典 private static readonly Dictionary<string, Product> CodeToProduct = BuildCodeMap(); // 构建映射的工具方法 private static Dictionary<string, Product> BuildCodeMap() { var map = new Dictionary<string, Product>(); foreach (var product in Products.Values) { foreach (var code in product.Codes) { // 若担心重复Code,可先判断:if (!map.ContainsKey(code)) map.Add(code, product); map.Add(code, product); } } return map; }
动态数据场景:同步维护映射
如果产品数据会动态增改,要同步维护Code映射字典,比如新增产品的方法:
public static void AddProduct(Product product) { if (!Products.ContainsKey(product.Id)) { Products.Add(product.Id, product); foreach (var code in product.Codes) { if (!CodeToProduct.ContainsKey(code)) { CodeToProduct.Add(code, product); } // 重复Code可根据业务需求选择抛异常、覆盖或忽略 } } }
步骤3:通过Code查询产品
有了映射字典,查询逻辑非常简洁:
public static Product GetProductByCode(string code) { CodeToProduct.TryGetValue(code, out var product); return product; // 未找到返回null,也可根据需求抛异常 }
补充说明
- 若业务允许一个Code对应多个产品,将
Dictionary<string, Product>改为Dictionary<string, List<Product>>,构建时往List中添加产品即可。 - 如果你的Code是数字类型(比如之前尝试的int数组),只需把字典键类型改成
int,逻辑完全一致。
内容的提问来源于stack exchange,提问作者collin
相关产品推荐
相关产品推荐

