合并重复金额

时间:2015-05-12 19:37:22

标签: c# json.net

假设我有这个JArray:

{
    "ArrayofItem":{
        "Item":[
        {
            "Amount": "1.52"
            "Date": "05/01/2015"
        },
        {
            "Amount": "2.52"
            "Date": "05/01/2015"
        },
        {
            "Amount": "5.62"
            "Date": "05/02/2015"
        },
        {
            "Amount": "1.06"
            "Date": "05/02/2015"
        },
        {
            "Amount": "6.30"
            "Date": "05/03/2015"
        },
        {
            "Amount": "1.00"
            "Date": "05/04/2015"
        },
        {
            "Amount": "1.55"
            "Date": "05/04/2015"
        },
        {
            "Amount": "1.63"
            "Date": "05/05/2015"
        },
        {
            "Amount": "1.78"
            "Date": "05/06/2015"
        }
    }
}   

如何合并项目以便将同一日期的所有项目组合在一起以创建一个新的JArray:

{
    "ArrayofItem":{
        "Item":[
        {
            "Amount": "4.04"
            "Date": "05/01/2015"
        },
        {
            "Amount": "6.68"
            "Date": "05/02/2015"
        },
        {
            "Amount": "6.30"
            "Date": "05/03/2015"
        },
        {
            "Amount": "2.55"
            "Date": "05/04/2015"
        },
        {
            "Amount": "1.63"
            "Date": "05/05/2015"
        },
        {
            "Amount": "1.78"
            "Date": "05/06/2015"
        }
    }
}   

基本上我需要按原始项目的日期列表进行汇总。您可以假设这些项目已按日期排序。

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码作为模型:

public class Rootobject
{
    public Arrayofitem ArrayofItem { get; set; }
}

public class Arrayofitem
{
    public Item[] Item { get; set; }
}

public class Item
{
    public string Amount { get; set; }
    public string Date { get; set; }
}

然后这段代码将完成工作:

string jsonText = "your json text goes here...";    
var o = JsonConvert.DeserializeObject<Rootobject>(jsonText);
var itemArray = o.ArrayofItem.Item
                             .GroupBy(item => item.Date, (date, item) => 
                                    new Item 
                                    { 
                                        Date = date, 
                                        Amount = item.Sum(i => float.Parse(i.Amount)).ToString() 
                                    }).ToArray();

string serializedGroup = JsonConvert.SerializeObject(new Rootobject { ArrayofItem = new Arrayofitem { Item = itemArray } });

答案 1 :(得分:0)

如果您想纯粹使用LINQ to JSON执行此操作,则可以使用GroupBySum创建必要的对象:

        var obj = JObject.Parse(json);
        var query = obj.SelectTokens("ArrayofItem.Item")
            .SelectMany(t => t)
            .OfType<JObject>()
            .GroupBy(o => o["Date"], o => o["Amount"])
            .Select(g => new JObject(new JProperty("Amount", g.Sum(a => (decimal)a)), new JProperty("Date", g.Key)));
        var newObj = new JObject(new JProperty("ArrayofItem", new JObject(new JProperty("Item", new JArray(query)))));