c# - 基于一个属性合并 2 个列表并连接其他属性

标签 c# linq join ienumerable sql-to-linq-conversion

IList<MyObject> ob1 = {new MyObject {Id = "1", Items = {BananaObject1, BananaObject2}}}  
IList<MyObject> ob2 = { new MyObject {Id = "1", Items = {BananaObject2, BananaObject3}},  
new MyObject {Id = "2", Items = {BananaObject3, BananaObject3}}}

我想合并 2 个列表,使得结果列表为

IList<MyObject> ob2 = { new MyObject {Id = "1", Items = {BananaObject1, BananaObject2, BananaObject3}},
new MyObject {Id = "2", Items = {BananaObject3, BananaObject3}}}

因此,由于两个列表的第一项的 id 相同,因此它们成为一个,并且它们的一个属性被连接起来。
我可以做一个 for 循环来实现这一点,但我正在为此寻找一个简洁的最佳性能 linq 表达式。

谢谢

最佳答案

Concat 列表在一起,GroupBy Id 属性,SelectMany 获取合并的项目列表:

ob1.Concat(ob2)
   .GroupBy(o => o.Id)
   .Select(g => new MyObject() 
   { 
      Id = g.Key, 
      Items = g.SelectMany(o => o.Items ).Distinct().ToList()
   });

关于c# - 基于一个属性合并 2 个列表并连接其他属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33023079/

相关文章:

c# - Interlock.Add() for double

performance - LINQ to Entities -- OrderBy().ToList() 与 ToList().OrderBy()

c# - 动态构建查询

sql - 多对多关系

php - 如何插入连接

C# Linq 快速计算列表中项目的有效方法

c# - 如何定义显示的数据?

c# - 字典的值 c# .net

IGrouping 的 C# 内联初始化

MySQL 根据另一个表的值更新表