[英]How to group C# class object values. Is this possible with LINQ?
I have been experimenting with grouping object fields and can't seem to get this working.我一直在尝试对 object 字段进行分组,但似乎无法使其正常工作。
Here is the class object这是 class object
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; }
The data is coming in via JSON from an API call as such:数据通过 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
},
] } ] }
No problems deserializing the object.反序列化 object 没有问题。
Request request = new Request("api/path/to/get/inventory/data", Method.GET);
var r= request.Execute<InventoryReport>();
Now I have a populated InventoryReport object.现在我有一个填充的 InventoryReport object。
What I need is to ignore the warehouse_id value and group the quantity data by product.我需要的是忽略warehouse_id 值并按产品对数量数据进行分组。
EX.前任。
"inventories": [{ "warehouse_id":"any value here", "product_id": "productA", "quantity": 5571 // Here we have grouped the total quantity by product },
The question is in two parts.问题分为两部分。 Is it possible to get this result with LINQ?
是否可以使用 LINQ 获得此结果? I tried this but it does not work (I am thinking because of the variable warehouse_ids.)
我试过了,但它不起作用(我在想是因为变量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 };
If not possible, what is the best way to approach this.如果不可能,解决此问题的最佳方法是什么。 I'm just not getting it so any guidance would be helpful.
我只是不明白,所以任何指导都会有所帮助。
Try this尝试这个
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) };
I think it is pretty self-explanatory.我认为这是不言自明的。 If you have questions, leave a comment.
如果您有任何疑问,请发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.