如何基于ID匹配规则从TableOne和TableTwo两个对象填充合并DTO
解决方案
你可以直接用LINQ的关联操作实现需求,不需要手动写循环遍历,效率更高也更简洁。
1. 内连接(仅返回两个表Id能匹配上的记录,符合「Id相等才填充」的要求)
public IEnumerable<TableOneAndTwoDTO> GetTableOneAndTwo() { var t1 = myRepository.GetTableOne(); var t2 = myRepository.GetTableTwo(); var result = from one in t1 join two in t2 on one.Id equals two.Id select new TableOneAndTwoDTO { IdTableOne = one.Id, ValueTableOne = one.Value, IdTableTwo = two.Id, ValueTableTwo = two.Value }; // 按需添加.ToList()立即执行查询,也可以直接返回IEnumerable return result.ToList(); }
2. 左连接(保留TableOne的所有记录,没有匹配的TableTwo记录时对应字段填默认值)
如果你需要保留TableOne的全部数据,不管有没有匹配的TableTwo记录,可以用左连接写法:
public IEnumerable<TableOneAndTwoDTO> GetTableOneAndTwo() { var t1 = myRepository.GetTableOne(); var t2 = myRepository.GetTableTwo(); var result = from one in t1 join two in t2 on one.Id equals two.Id into temp from twoItem in temp.DefaultIfEmpty() select new TableOneAndTwoDTO { IdTableOne = one.Id, ValueTableOne = one.Value, IdTableTwo = twoItem?.Id ?? 0, ValueTableTwo = twoItem?.Value ?? string.Empty }; return result.ToList(); }
注意事项
如果你的仓储层返回的是IQueryable类型(比如EF/EF Core场景),上述关联操作会直接翻译成SQL在数据库层面执行,比把全量数据加载到内存再关联的性能高很多。
如果你坚持要沿用原来的循环写法,也可以在循环中匹配对应Id的TableTwo记录,不过这种方式时间复杂度更高,不推荐数据量大的场景使用:
foreach (var item in query) { var matchT2 = t2.FirstOrDefault(x => x.Id == item.IdTableOne); combination.Add(new TableOneAndTwoDTO { IdTableOne = item.IdTableOne, ValueTableOne = item.ValueTableOne, IdTableTwo = matchT2?.Id ?? 0, ValueTableTwo = matchT2?.Value ?? string.Empty }); }
内容的提问来源于stack exchange,提问作者User1899289003
相关产品推荐
相关产品推荐

