C# Dedupe a List with a List and Combine the List

Viewed 60

What is the best way to dedupe a list with a list? rough class example:

Class CustomType{
 string prop1
 string prop2
 string prop3
 int quantity
 List<AnotherCustomType> serials
}

So I have a list of CustomType objects. I started trying to do a group by but got hung up on the list. I need to combine items in the list with the same prop1 and prop2 and combine their lists (serials) and combined quantities.

I started down this road...

 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
}

Am I way off?

1 Answers

You could use the method SelectMany to flatten 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();
Related