ASP.NET MVC中Dictionary重复键问题:如何为重复键添加数字实现唯一化
解决Dictionary重复键问题:自动生成唯一键
嘿,我懂你现在遇到的麻烦——你当前的代码不管键是否存在都直接执行Add操作,这难怪会触发「An item with the same key has already been added.」的异常!咱们来调整下逻辑,实现当目标键已存在时,自动在键名后加递增数字生成唯一键的功能。
第一步:写个生成唯一键的辅助方法
先搞个小方法帮我们找到可用的唯一键,逻辑很直白:从原始键开始检查,要是已经存在就追加递增数字,直到找到一个没被用过的键为止。
// 把YourValueType换成你Dictionary里值的实际类型(比如redBlue对应的类型) private string GetUniqueKey(Dictionary<string, YourValueType> targetDict, string baseKey) { string currentCandidateKey = baseKey; int counter = 1; // 循环检查,直到找到不存在的键 while (targetDict.ContainsKey(currentCandidateKey)) { currentCandidateKey = $"{baseKey}{counter}"; counter++; } return currentCandidateKey; }
第二步:修改你的添加逻辑
把原来的if-else替换成调用这个方法,确保每次添加的键都是唯一的:
// 如果model不是字符串类型,先转成字符串;如果本身是string,直接用model即可 string originalKey = model.ToString(); // 获取确保唯一的键 string uniqueKey = GetUniqueKey(RedBlueData, originalKey); // 直接添加,不用再做重复判断 RedBlueData.Add(uniqueKey, redBlue);
效果演示
比如你的原始键是"Item":
- 第一次添加:键为
"Item" - 第二次添加:键自动变成
"Item1" - 第三次添加:键变成
"Item2" - 以此类推,再也不会出现重复键的问题啦!
小提醒
如果你的model本身就是字符串类型,那originalKey = model就行,不用额外转ToString。另外记得把方法里的YourValueType替换成你Dictionary中值的实际类型(比如RedBlueData是Dictionary<string, RedBlueModel>的话,就换成RedBlueModel)。
内容的提问来源于stack exchange,提问作者user979331
相关产品推荐
相关产品推荐

