我一直在尝试对对象字段进行分组,但似乎无法正常工作。
这是类对象
public class Inventory
{
public string warehouse_id { get; set; }
public string product_id { get; set; }
public int quantity { get; set; }
}
public List<Inventory> inventories { get; set; }
数据通过 API 调用通过 JSON 传入:
{
"inventories": [{
"warehouse_id": "warehouse1",
"product_id": "productA",
"quantity": 5400
}, {
"warehouse_id": "warehouse2",
"product_id": "productA",
"quantity": 571
}, {
"warehouse_id": "warehouse3",
"product_id": "productA",
"quantity": 0
}, {
"warehouse_id": "warehouse1",
"product_id": "prod_B",
"quantity": 0
}, {
"warehouse_id": "warehouse2",
"product_id": "prod_B",
"quantity": 0
}, {
"warehouse_id": "warehouse3",
"product_id": "prod_B",
"quantity": 1
},
] }
反序列化对象没有问题。
Request request = new Request("api/path/to/get/inventory/data", Method.GET);
var r= request.Execute<InventoryReport>();
现在我有一个填充的 InventoryReport 对象。
我需要的是忽略warehouse_id值并按产品对数量数据进行分组。
前任。 “库存”:[{
"warehouse_id":"此处任意值",
"product_id": "产品A",
"quantity": 5571//这里我们按产品对总数量进行了分组
},
问题分为两部分。用LINQ可以得到这个结果吗?我尝试了这个,但它不起作用(我想是因为变量warehouse_ids。)
var groupedInventory = from newObject1 in r.inventories
group arrayObject1 by new { newObject1.quantity, newObject1.product_id }
into g
select new { KKey = g.Key, Obj = g };
如果不可能,解决这个问题的最佳方法是什么。我只是不明白,所以任何指导都会有帮助。
最佳答案
试试这个
var groupedInventory = from obj in r.inventories
group obj by obj.product_id into g
select new Inventory() { product_id = g.Key, quantity = g.Sum(e => e.quantity) };
我认为这是不言自明的。如果您有疑问,请发表评论。
关于c# - 如何对 C# 类对象值进行分组。这可以用 LINQ 实现吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58532642/