获得平均总和

时间:2013-02-22 17:15:16

标签: c# linq

示例集合:

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 });

产品数量未知。因此,我需要获得每个不同产品的百分比/总数,然后是所有产品的平均值。在这种情况下:

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

我们可以用Linq做到这一点,我只对Linq解决方案感兴趣。

2 个答案:

答案 0 :(得分:2)

这样的东西?

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);

请注意,Avg的答案应为0.717而不是7.17

答案 1 :(得分:2)

试试这个:

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