如何解决将两个列表项合并为一个项
我正在尝试根据 productId 连接列表项。为JSON命名表示歉意,我知道这不是最好的方法,我无法控制。
如果列表中的项目具有相同的productId,我想将它们连接起来,并使用包含变量属性(即 costType , > feeId , feeName 等(请参见所需结果)。当productId相同时,branchName,branchId,productName和bundle将具有相同的值。
[{
"branchname": "Branch","branchid": "b7d79617-1c36-4be1-87b7-d7a910a5b72e","productid": "d029d731-92a6-4bd3-b020-1ad282af8308","productname": "Local Search","bundle": false,"costtype": "Cost","feeid": "c3d5fb93-f8be-4be2-b5b8-dd1701614e05","feename": "Fee","discounttype": null,"discountamount": null,"baseprice": 20,"grossprice": 20,"vatrate": 20,"vatamount": 4,"netprice": 24
},{
"branchname": "Branch","costtype": "Sale","feeid": "7299a1fe-fe3d-43e2-b21a-3710e1bcd720","feename": "Standard Product Fee","baseprice": 60,"grossprice": 60,"vatamount": 12,"netprice": 72
}
]
所需结果:
[{
"branchname": "Branch","fees": [{
"costtype": "Cost","netprice": 24
},{
"costtype": "Sale","netprice": 72
}
]
}
]
我尝试按productId进行分组,即list.GroupBy(g => g.ProductId)
,但是我不确定下一步该怎么做。如果可能,我正在寻找一种优雅的LINQ解决方案。
解决方法
您可以通过以下查询将列表转换为新格式:
var condensed =
list.GroupBy(p => p.ProductId)
.Select(g =>
{
var first = g.First();
return new
{
first.BranchName,first.BranchId,first.ProductId,first.ProductName,first.Bundle,fees = g.Select(p => new
{
p.CostType,p.FeeId,p.FeeName,p.DiscountType,p.DiscountAmount,p.BasePrice,p.GrossPrice,p.VatRate,p.VatAmount,p.NetPrice
})
.ToList()
};
})
.ToList();
这是一个有效的演示:https://dotnetfiddle.net/tweKHY
,要生成与您想要的输出类似的输出-并在此过程中进行一些假设-尝试执行以下操作:
list.GroupBy(item => item.ProductId /*,<your value selector lambda goes here which only returns a tuple composed of what goes as children of "fee" element> */).Select(g =>
{
var item = g.First();
return new { item.BranchName,item.BranchId,item.ProductId,item.ProductName,item.Bundle };
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。