Goran
Goran

Reputation: 6518

Getting average of sums

Example collection:

List<Product> list = new List<Product>();
list.Add(new Product { Id = 1, Good = 50, Total = 50 });
list.Add(new Product { Id = 2, Good = 18, Total = 30 });
list.Add(new Product { Id = 2, Good = 15, Total = 30 });
list.Add(new Product { Id = 1, Good = 40, Total = 50 });
list.Add(new Product { Id = 3, Good = 6, Total = 10 });
list.Add(new Product { Id = 1, Good = 45, Total = 50 });
list.Add(new Product { Id = 3, Good = 8, Total = 10 });

Number of products is unknown. What I need as a result is to get a percentage for each distinct product good/total, and then an average for all products. In this case:

Product Id=1, GoodSum = 50 + 40 + 45 = 135, TotalSum = 50 + 50 + 50 = 150, Perc = 135/150
Product Id=2, GoodSum = 18 + 15 = 33, TotalSum = 30 + 30 = 60, Perc = 33/60
Product Id=3, GoodSum = 6 + 8 = 14, TotalSum = 10 + 10 = 20, Perc = 14/20

Avg = Avg(135/150 + 35/60 + 14/20) = Avg(0.9 + 0.55 + 0.7) = 2.15 / 3 = 7.17

Can we do this with Linq, I am only interested in Linq solution.

Upvotes: 0

Views: 96

Answers (2)

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14282

Try this :

var avg = list.GroupBy(G => G.Id)
              .Select(G => (G.Sum(T => T.Good)/G.Sum(T => T.TotalSum)))
              .Average();

Upvotes: 2

D Stanley
D Stanley

Reputation: 152511

Something like this?

var groups = list.GroupBy(l => l.Id)
                 .Select(g => new {
                                      Id = g.Key, 
                                      GoodSum = g.Sum(i=>i.Good), 
                                      TotalSum= g.Sum(i=>i.Total),
                                      Perc = (double) g.Sum(i=>i.Good) / g.Sum(i=>i.Total)
                                  }
                        );

 var average = groups.Average(g=>g.Perc);

Note that your answer for Avg should be 0.717 not 7.17.

Upvotes: 2

Related Questions