-3

Trying to group by multiple fileds but having issues with it. I want to group by period,productcode.

var ProductUsageSummary = from b in myProductUsage
                            group b by b.ProductCode into g
                            select new
                            {
                                Period = g.Key,
                                Code = g.Key,
                                Count = g.Count(),
                                TotalQty = g.Sum(n => n.Qty),
                                Price = g.Average(n => n.Price)
                            };

also tried

var ProductUsageSummary = from b in myProductUsage
                            group b by b.Period b.ProductCode into g
                            select new
                            {
                                Period = g.Key(n => n.period),
                                Code = g.Key,
                                Count = g.Count(),
                                TotalQty = g.Sum(n => n.Qty),
                                Price = g.Average(n => n.Price)
                            };
Zein Makki
  • 29,485
  • 6
  • 52
  • 63
user2520306
  • 27
  • 1
  • 9

2 Answers2

2

You could create an anonymouns object to to group on multiple columns (ex... new {prop1 prop2}) , and the grouped fields can be accessed by Key.PropertyName

Try this.

var ProductUsageSummary = from b in myProductUsage
                          group b by new { b.Period,  b.ProductCode }into g
                          select new
                          {
                              Period= g.Key.Period,
                              Code = g.Key.ProductCode ,
                              Count = g.Count(),
                              TotalQty = g.Sum(n => n.Qty),
                              Price = g.Average(n => n.Price)
                          };
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
1

This is the correct syntax using Anonymous Types :

group b by new { b.ProductCode, b.Period } into g

Then in select:

g.Key.ProductCode and g.Key.Period

Full Query:

var ProductUsageSummary = from b in myProductUsage
                          group b by new { b.Period b.ProductCode } into g
                          select new
                          {
                              Period = g.Key.Period,
                              Code = g.Key.ProductCode,
                              Count = g.Count(),
                              TotalQty = g.Sum(n => n.Qty),
                              Price = g.Average(n => n.Price)
                          };
Zein Makki
  • 29,485
  • 6
  • 52
  • 63