0

示例集合:

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 解决方案感兴趣。

4

2 回答 2

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.717not 7.17

于 2013-02-22T17:20:37.877 回答
2

尝试这个 :

var avg = list.GroupBy(G => G.Id)
              .Select(G => (G.Sum(T => T.Good)/G.Sum(T => T.TotalSum)))
              .Average();
于 2013-02-22T17:22:42.723 回答