-2

I want to group list of my objects and sum their totals so basically at the end results might looks like this:

1 Coca cola 3x 15.00$
2 Pepsi 1x 5.00$

instead of this:

1 Coca Cola 2x 10.00$
2 Pepsi     1x 5.00$
3 Coca Cola 1x 5.00$

Here is my code:

  List<Product> result = productsList
                    .GroupBy(l => l.Article.Title)
                    .Select(cl => new Product
                    {
                        // Avoid assigning all the properties somehow?
                        TotalAmount = cl.Sum(c => c.TotalAmount),
                    }).ToList();

My Product class has like 20 properties and I would like to avoid populating all of them but I want to keep their values as they are (I dont want to lose values of other properties).

So is this possible to achieve if I want to group products and change their TotalAmount as I want to sum them and that's it.

Is this possible somehow?

Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102
  • 1
    You probably want to generate some code that will use the same set of properties for `GroupBy` and creating your `Product` objects... and add proper *deep clone* to `Product... There really nothing built in for it – Alexei Levenkov Nov 25 '19 at 21:44
  • @AlexeiLevenkov May you post an example of that so I might accept it as answer, that would be probably useful to many people. Thanks Alexei – Roxy'Pro Nov 25 '19 at 21:45

1 Answers1

2

I think it is possible only by mapping properties using reflaction. https://stackoverflow.com/a/8724150

Then, change TotalAmount of new istance of object... something like that:

var result = productsList
            .GroupBy(l => l.Article.Title)
            .Select(cl => 
            {
                    var product = new Product();
                    Reflection.CopyProperties(cl.First(), product);
                    product.TotalAmount = cl.Sum(c => c.TotalAmount);
                    return product;
            }).ToList();

Alternatively you can map result in a new class type:

var result = productsList
            .GroupBy(l => l.Article.Title)
            .Select(cl => new ProductItem
            {
                Product = cl.First(),
                TotalAmount = cl.Sum(c => c.TotalAmount),
            }).ToList();
Simone S.
  • 1,756
  • 17
  • 18
  • 1
    Good stating point for general solution. Note that to have sensible behavior in general case `GroupBy` and "shared" properties need to match otherwise you overwrite some other properties like {"cola", $3, in cans}, {"cola", $5, in bottles} produces {"cola", $8, in cans} which is probably unexpected result (maybe {"cola", $8, undefined} is better - depends). Writing such code is exercise for reader :) – Alexei Levenkov Nov 25 '19 at 23:19