用列表对列表进行重复数据消除的最佳方法是什么?粗略类示例:
Class CustomType{
string prop1
string prop2
string prop3
int quantity
List<AnotherCustomType> serials
}
所以我有一个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
}
我离这儿很远吗?
您可以使用方法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();