[英]parsing JSON data with LINQ
因此,我有一些數據,如下所示:
[
{
"Name": "Jonh ",
"Order": [
{
"Product": {
"Id": 8
},
"Quantity": 1
},
{
"Product": {
"Id": 19
},
"Quantity": 8
}
]
},
{
"Name": "Jane Doe 1",
"Order": [
{
"Product": {
"Id": 26
},
"Quantity": 7
},
{
"Product": {
"Id": 44
},
"Quantity": 2
},
{
"Product": {
"Id": 21
},
"Quantity": 6
},
{
"Product": {
"Id": 48
},
"Quantity": 2
},
{
"Product": {
"Id": 35
},
"Quantity": 2
},
{
"Product": {
"Id": 43
},
"Quantity": 1
}
]
}
]
更新:JSON已經使用NewtonSoft.Json.JsonConvert進行了解析
我對Linq完全陌生,我能夠用JavaScript做到這一點。 我需要一個linq查詢,以提取最暢銷商品訂購的商品;
因此:它將所有產品匯總在一起,然后將銷售數量相加,然后將訂單數量相加。
這就是我現在所擁有的:
var products = clientSales.SelectMany(m => m.Order).Select(f=>f.Product.Id).Distinct();
這給了我一系列不同的productIds ...
您幾乎是正確的,首先應該在Order中使用SelectMany,然后在數量中使用OrderByDescending,最后選擇Select以獲取產品ID,例如以下代碼:
var products = clientSales.SelectMany(m => m.Order)
.OrderByDescending(x => x.Quantity)
.Select(p => p.Product.Id)
.Distinct();
輸出:
19
26
21
44
48
35
8
43
您可以在這里看到它的工作: https : //dotnetfiddle.net/6sb3VY
假設您有以下課程:
public class Customer
{
public string Name { get; set; }
public List<Item> Order { get; set; }
}
public class Item
{
public Product Product { get; set; }
public int Quantity { get; set; }
}
public class Product
{
public int Id { get; set; }
}
您可以生成產品ID列表以及按數量降序訂購的已售數量,其數量如下:
string json = "[{\"Name\": \"Jonh \",\"Order\": [{\"Product\": {\"Id\": 8},\"Quantity\": 1},{\"Product\": {\"Id\": 19},\"Quantity\": 8}]},{\"Name\": \"Jane Doe 1\",\"Order\": [{\"Product\": {\"Id\": 26},\"Quantity\": 7},{\"Product\": {\"Id\": 44},\"Quantity\": 2},{\"Product\": {\"Id\": 21},\"Quantity\": 6},{\"Product\": {\"Id\": 48},\"Quantity\": 2},{\"Product\": {\"Id\": 35},\"Quantity\": 2},{\"Product\": {\"Id\": 43},\"Quantity\": 1}]}]";
var deserializedObject = JsonConvert.DeserializeObject<List<Customer>>(json);
var groupedProducts = from product in deserializedObject.SelectMany(c => c.Order)
group product by product.Product.Id into grpProduct
select new
{
ProductId = grpProduct.Key,
Quantity = grpProduct.ToList().Sum(p => p.Quantity)
};
// Produces the ordered list of product IDs and quantity sold sorted by quantity descending
var orderedProducts = groupedProducts.OrderByDescending(p => p.Quantity).ToList();
最終將根據您的輸入生成以下匿名對象列表:
Product ID Quantity
19 8
26 7
21 6
44 2
48 2
35 2
8 1
43 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.