0

我需要有关此功能的帮助:

var ListFruits = Enumerable.From(data) 
    .GroupBy("$.Fruits", "", "d,v => { Fruits:d,NumberFruits:v.Sum('$.NumberFruits|0')}") 
    .Select(" $.Fruits+ ': ' + $.NumberFruits") 
    .ToArray();
// result is [apple: 2 , banana:5 , orange: 3]

我希望每种水果占总数的百分比

执行此类操作的函数(total所有水果的总和在哪里):

var ListFruits = Enumerable.From(data) 
    .GroupBy("$.Fruits", "", "d,v => { Fruits:d,NumberFruits:v.Sum('$.NumberFruits|0')}") 
    .Select(" $.Fruits+ ': ' + $.NumberFruits + 'is' + ($.NumberFruits/total)*100  ") 
    .ToArray();
// result is [apple: 2 is 20% , banana: 5 is 50% , orange: 3 is 30%]
4

1 回答 1

0

好吧,你必须计算总数。使用该Let()功能可以帮助保持清洁。

var data = [
    { Fruit: 'apple', Count: 2 },
    { Fruit: 'banana', Count: 5 },
    { Fruit: 'orange', Count: 3 }
];
var query = Enumerable.From(data)
    .Let(function (d) {
        var total = d.Sum("$.Count");
        return d.GroupBy("$.Fruit", "$.Count", function (f, g) {
            var sum = g.Sum(),
                percent = (sum / total) * 100;
            return f + ': ' + sum + ' is ' + percent + '%';
        });
    })
    .ToArray();

这将产生以下数组:

[
  "apple: 2 is 20%",
  "banana: 5 is 50%",
  "orange: 3 is 30%"
]
于 2015-07-24T05:27:52.153 回答