C#实现:通过主键外键匹配从另一列表更新对象details属性
匹配主键更新对象详情
我有两个对象列表,结构分别如下:
第一个列表:
"result": [ { "primaryKey": "123", "count": 0, "details": [ { "employeeName": "Chris" } ] }, { "primaryKey": "456", "count": 10, "details": [ { "employeeName": "Nick" } ] } ]
第二个列表:
"result": [ { "foreignKey": "123", "details": [ { "employeeName": "Sean" } ] }, { "foreignKey": "789", "details": [ { "employeeName": "Andrew" } ] } ]
需求:当第一个列表的primaryKey与第二个列表的foreignKey匹配时,用第二个列表的details内容更新第一个列表对应对象的details属性。
实现思路
- 先将第二个列表转换为以
foreignKey为键、details为值的映射表,避免嵌套循环,提升匹配效率 - 遍历第一个列表的每个对象,检查映射表中是否存在对应主键,存在则直接更新
details属性
代码示例(JavaScript)
// 定义两个原始列表 const list1 = [ { "primaryKey": "123", "count": 0, "details": [{"employeeName": "Chris"}] }, { "primaryKey": "456", "count": 10, "details": [{"employeeName": "Nick"}] } ]; const list2 = [ { "foreignKey": "123", "details": [{"employeeName": "Sean"}] }, { "foreignKey": "789", "details": [{"employeeName": "Andrew"}] } ]; // 构建映射表 const detailsMap = new Map(list2.map(item => [item.foreignKey, item.details])); // 遍历更新第一个列表 list1.forEach(item => { if (detailsMap.has(item.primaryKey)) { item.details = detailsMap.get(item.primaryKey); } }); // 输出更新后的结果 console.log(list1);
更新后结果
[ { "primaryKey": "123", "count": 0, "details": [{"employeeName": "Sean"}] }, { "primaryKey": "456", "count": 10, "details": [{"employeeName": "Nick"}] } ]
内容的提问来源于stack exchange,提问作者rfa
相关产品推荐
相关产品推荐

