2013-02-22 62 views
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的解決方案感興趣。

回答

2

試試這個:

var avg = list.GroupBy(G => G.Id) 
       .Select(G => (G.Sum(T => T.Good)/G.Sum(T => T.TotalSum))) 
       .Average(); 
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