3

How to group by then sum inside the list below is my sample code:

List<BrandType> brandTypeList = new List<BrandType>();

BrandType brandTypeClass = new BrandType();
brandTypeClass.Amount = 100;
brandTypeClass.Count = 50;
brandTypeClass.Category = "Fish";
brandTypeList.Add(brandTypeClass);

BrandType brandTypeClass2 = new BrandType();
brandTypeClass2.Amount = 100;
brandTypeClass2.Count = 50;
brandTypeClass2.Category = "Fish";
brandTypeList.Add(brandTypeClass2);

BrandType brandTypeClass3 = new BrandType();
brandTypeClass3.Amount = 100;
brandTypeClass3.Count = 50;
brandTypeClass3.Category = "Pork";
brandTypeList.Add(brandTypeClass3);
    brandTypeList.GroupBy(x => new { x.Category }).Select
(x => new { Category = x.Key.Category, 
Amount = x.Sum(z => z.Amount), 
Count = x.Sum(z => z.Count) });

Here's what it looks like

[0] {Amount = 100, Category = "Pork", Count = 50}
[1] {Amount = 100, Category = "Fish", Count = 50}
[2] {Amount = 100, Category = "Fish", Count = 50}

How can I SUM the amout and count then group by Category? I want the result to be

Amount = 200, Category = "Fish", Count = 100

Amount = 100, Category = "Pork" Count = 50

1 Answers1

4

The following code snippet will work for you:

var result = from brand in brandTypeList
            group brand by brand.Category into grp
            select new
            {
                Category = grp.Key,
                Amount = grp.Sum(z => z.Amount),
                Count = grp.Sum(z => z.Count)
            };

This one also works fine:

var result = brandTypeList.GroupBy(x => x.Category).Select
(y => new {
    Category = y.Key,
    Amount = y.Sum(z => z.Amount),
    Count = y.Sum(z => z.Count)
});

It turns out that your code also works fine, probably the problem is that you expect list to be modified inplace, but linq does not produce side effects and new IEnumerable will be created and you need to save results to variable.

Access Denied
  • 8,723
  • 4
  • 42
  • 72