如何在C#中基于Type ID为SQL分组数据分配递增整数
C#实现按Type ID分配唯一递增整数方案
实现思路
核心是用字典缓存已经出现过的分组标识对应的分配值,遍历数据时匹配缓存,命中则直接赋值,未命中则分配新的递增值并存入缓存,保证同一分组对应同一整数值。
具体实现步骤
- 定义数据映射实体
public class VehicleFeature { public string Type { get; set; } public int TypeId { get; set; } public string Features { get; set; } public string Values { get; set; } // 待赋值的递增整数字段 public int AssignedInt { get; set; } }
- 编写核心分配逻辑
// 假设从数据库查询得到的原始数据列表 List<VehicleFeature> dataList = QueryDataFromDatabase(); // 初始化字典:Key为Type ID,Value为分配的递增整数 Dictionary<int, int> typeIdMapping = new Dictionary<int, int>(); // 递增起始值,从1开始 int currentAssignValue = 1; // 遍历所有数据 foreach (var item in dataList) { // 已存在该Type ID的映射,直接赋值 if (typeIdMapping.TryGetValue(item.TypeId, out int assignedVal)) { item.AssignedInt = assignedVal; } // 新的Type ID,分配新值并更新缓存 else { item.AssignedInt = currentAssignValue; typeIdMapping.Add(item.TypeId, currentAssignValue); currentAssignValue++; } } // 处理完成后,如果需要回写数据库,直接批量更新dataList即可
补充说明
- 如果需要按Type+Type ID联合分组作为唯一标识,只需将字典Key改为联合键即可,示例:
// 初始化联合键字典 Dictionary<(string Type, int TypeId), int> typeMapping = new Dictionary<(string Type, int TypeId), int>(); // 判断逻辑调整为 if (typeMapping.TryGetValue((item.Type, item.TypeId), out int assignedVal)) { item.AssignedInt = assignedVal; } else { item.AssignedInt = currentAssignValue; typeMapping.Add((item.Type, item.TypeId), currentAssignValue); currentAssignValue++; }
- 如果需要按特定规则(比如Type名称排序、Type ID大小排序)决定递增顺序,只需要在遍历前对
dataList做对应排序即可,比如dataList = dataList.OrderBy(x => x.Type).ThenBy(x => x.TypeId).ToList(); - 如果Type ID是字符串类型,只需要把字典的Key类型调整为对应字符串类型即可,逻辑无需改动
- 处理百万级以内的数据时,字典的查找性能不会有明显瓶颈,无需额外优化
内容的提问来源于stack exchange,提问作者Bell Frajer
相关产品推荐
相关产品推荐

