如何在C#中按ID全外连接两个列表并映射为合并属性对象
C# 实现双列表按ID合并并保留无匹配记录
现有两个列表List<Model1>和List<Model2>,需要合并成包含双方所有属性的List<Model1and2>,规则如下:
- 将ID匹配的记录合并为一条完整记录
- 无匹配ID的记录单独保留,缺失的属性留空
第一步:定义模型类
首先明确三个模型的结构:
public class Model1 { public string id { get; set; } public string name { get; set; } public string surName { get; set; } } public class Model2 { public string id { get; set; } public string email { get; set; } public string phone { get; set; } } public class Model1and2 { public string id { get; set; } public string name { get; set; } public string surName { get; set; } public string email { get; set; } public string phone { get; set; } }
第二步:实现合并逻辑
通过LINQ可以简洁完成合并操作,核心思路是先获取所有唯一ID,再逐个匹配构建新对象:
// 初始化示例数据 List<Model1> m1List = new List<Model1> { new Model1 { id = "1", name = "a", surName = "b" }, new Model1 { id = "2", name = "c", surName = "d" }, new Model1 { id = "5", name = "e", surName = "f" } }; List<Model2> m2List = new List<Model2> { new Model2 { id = "1", email = "aa@gmail.com", phone = "555" }, new Model2 { id = "2", email = "bb@gmail.com", phone = "44" }, new Model2 { id = "3", email = "cc@gmail.com", phone = "77" } }; // 获取两个列表中所有不重复的ID var allUniqueIds = m1List.Select(m => m.id).Union(m2List.Select(m => m.id)); // 遍历所有ID,构建合并后的列表 List<Model1and2> m1Andm2List = allUniqueIds.Select(id => { // 查找当前ID对应的Model1和Model2记录 var matchedModel1 = m1List.FirstOrDefault(m => m.id == id); var matchedModel2 = m2List.FirstOrDefault(m => m.id == id); // 构建Model1and2对象,无匹配的属性赋值为空字符串 return new Model1and2 { id = id, name = matchedModel1?.name ?? string.Empty, surName = matchedModel1?.surName ?? string.Empty, email = matchedModel2?.email ?? string.Empty, phone = matchedModel2?.phone ?? string.Empty }; }).ToList();
逻辑说明
- 收集所有唯一ID:使用
Union方法合并两个列表的ID并去重,确保不会漏掉任何一条记录; - 匹配对应记录:用
FirstOrDefault查找当前ID对应的记录,无匹配时返回null; - 属性赋值:通过空合并运算符
??,当记录为null时,将对应属性设为空字符串,符合需求要求。
内容的提问来源于stack exchange,提问作者joe
相关产品推荐
相关产品推荐

