Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 求和的平均值_C#_Linq - Fatal编程技术网

C# 求和的平均值

C# 求和的平均值,c#,linq,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 Produc

示例集合:

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 });
我只对Linq解决方案感兴趣。

类似的东西

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

类似的答案

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

尝试以下方法:

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

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