linqjs group by with a sum

余生长醉 提交于 2019-11-27 19:03:38

问题


This might seems like an easy question but I'm struggling with the linqjs syntax.

Given the following basic JSON:

{
        "DateEvent": "2013-04-23 14:00:00Z",
        "DateRecord": "2013-04-23 14:00:00Z",
        "Amount": -9500,
        "Type": {
            "Description": "Capital"
        },
        "Currency": {
            "ID": "USD",
        }
}

Using linqjs how can I return the total for each currency?

Enumerable.From(data)
    .GroupBy("{ currency: $.Currency.ID }", null, 
        function (key, g) {
            var result = {
                    currency: key.currency,
                    total: g.Sum($.Amount)
                }});

The code above doesn't work.


回答1:


You almost had it. Your key selector in your GroupBy and Sum is incorrect. Also the key selector needs to be a string. Try the following:

var result = Enumerable.From(data).GroupBy("$.Currency.ID", null,
    function (key, g) {
        var result = {
            currency: key,
            total: g.Sum("$.Amount")
        }
        return result;
    }).ToArray();



回答2:


Just to expand further on this question.

The following syntax will group the data by an additional field:

var result = Enumerable.From(data)
                       .GroupBy("{ currency: $.Currency.ID, type: $.Type.Description }", null,
                            function (key, g) {
                                var result = {
                                     currency: key.currency,
                                     type: key.type,
                                     total: g.Sum("$.Amount")
                                }
                                return result;
                                }, function (x) { return x.currency + ':' + x.type }).ToArray();



回答3:


Assuming you have an array of objects that looks like that, you can write your query like this:

var query = Enumerable.From(data)
    .GroupBy(
        "{ Currency: $.Currency.ID, Type: $.Type.Description }",
        "$.Amount",
        "{ Currency: $.Currency, Type: $.Type, Total: $$.Sum() }"
    )
    .ToArray();

Personally I find using the lambda string syntax more succinct and preferable. Mixing lambdas and functions leads to messier code IMHO.




回答4:


I am the author of the open source project http://www.jinqJs.com

You could easily do it by executing:

jinqJs().from(data).groupBy('Currency').sum('Amount').select();


来源:https://stackoverflow.com/questions/17824008/linqjs-group-by-with-a-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!