C# 对列表和列表进行重复数据删除并合并列表

Jos*_*ers 2 .net c# linq

使用列表对列表进行重复数据删除的最佳方法是什么?粗略类示例:

Class CustomType{
 string prop1
 string prop2
 string prop3
 int quantity
 List<AnotherCustomType> serials
}
Run Code Online (Sandbox Code Playgroud)

所以我有一个 CustomType 对象列表。我开始尝试做一个小组,但被挂在名单上。我需要将列表中的项目与相同的 prop1 和 prop2 组合起来,并组合它们的列表(序列)和组合数量。

我开始走这条路...

 List<CustomType> c = (from x in items
                                  group x by new {
                                      x.prop1, x.prop2
                                  } into y
                                  select new CustomType {
                                  quantity = y.Sum(z => z.quantity),
                                  prop1 = y.prop1,
                                  prop2=y.prop2,
                                  prop3 = y.prop3,
                                  serials= ????? how do I combine the lists
}

Run Code Online (Sandbox Code Playgroud)

我离题了吗?

小智 5

您可以使用该方法SelectMany展平serials

List<CustomType> c = (from x in items
                            group x by new
                            {
                                x.prop1,
                                x.prop2
                            } into y
                            select new CustomType
                            {
                                quantity = y.Sum(z => z.quantity),
                                prop1 = y.Key.prop1,
                                prop2 = y.Key.prop2,
                                prop3 = y.First().prop3,
                                serials = y.SelectMany(item => item.serials).ToList()
                            }).ToList();
Run Code Online (Sandbox Code Playgroud)