计算JSON记录列表中的值并写入字典

  • 本文关键字:字典 JSON 记录 列表 计算 c#
  • 更新时间 :
  • 英文 :


我正在读取一个具有以下简单结构的JSON文件,我需要为具有相同"订单号"字段的每条记录统计"订单数量",并将总数存储在另一个查找列表中,每个"订单号"都有一条记录。输入文件看起来像

[
{
"Ord No": "41035",
"Ord Date": "05/06/2021",
"Stock No": "TW2807",
"Ord Qty": "3"
},
{
"Ord No": "41035",
"Ord Date": "05/06/2021",
"Stock No": "TW2809",
"Ord Qty": "1"
},
{
"Ord No": "41035",
"Ord Date": "05/06/2021",
"Stock No": "TW280S",
"Ord Qty": "3"
},
{
"Ord No": "41034",
"Ord Date": "05/06/2021",
"Stock No": "TW290L",
"Ord Qty": "17"
},
{
"Ord No": "41034",
"Ord Date": "05/06/2021",
"Stock No": "TW2830S",
"Ord Qty": "2"
},
{
"Ord No": "41034",
"Ord Date": "05/06/2021",
"Stock No": "CCDW12",
"Ord Qty": "15"
},
{
"Ord No": "41034",
"Ord Date": "05/06/2021",
"Stock No": "APXCSS",
"Ord Qty": "12"
}
]

我需要将数据转换为另一种结构,并能够使用密钥对(即(引用它

public class OrderTally
{
public string OrdNo { get; set; }
public string TotalOrdQty { get; set; }
}

对于结构,我希望最终得到这个,我将使用它作为查找。

[
{
"Ord No": "41035",
"Total Ord Qty": "7"
},
{
"Ord No": "41034",
"Total Ord Qty": "29"
}
]

我最初以为我需要使用系统。集合。Dictionary类正在做这件事,但到目前为止我生成的代码甚至还没有让我接近成功计算新记录数量的水平。

我正在将序列化的JSON读取为字符串,并按照以下进行解析

public class OrdsIn
{
[JsonProperty("Ord No")]
public string OrderNo { get; set; }
[JsonProperty("Ord Date")]
public string OrderDate { get; set; }
[JsonProperty("Stock No")]
public string StockNo { get; set; }
[JsonProperty("Ord Qty")]
public string Quantity { get; set; }
}

List<Order> OrdsIn = JsonConvert.DeserializeObject<List<Order>>(inString);
Dictionary<string, List<OrderTally>> keyup = new Dictionary<string, List<OrderTally>>();

这可以通过使用以下3个类轻松解决。

public class OrderRecord
{
[JsonProperty(PropertyName = "Ord No")]
public int OrdNo { get; set; }
[JsonProperty(PropertyName = "Ord Date")]
public DateTime OrdDate { get; set; }
[JsonProperty(PropertyName = "Stock No")]
public string StockNo { get; set; }
[JsonProperty(PropertyName = "Ord Qty")]
public int OrdQty { get; set; }
}
public class OrderTally
{
[JsonProperty(PropertyName = "Ord No")]
public string OrdNo { get; set; }
[JsonProperty(PropertyName = "Total Ord Qty")]
public string TotalOrdQty { get; set; }
}
public class JsonUtils
{
public static string GetJsonOfOrderTally(string strJsonRecords)
{
List<OrderRecord> lstOrderRecord = JsonConvert.DeserializeObject<List<OrderRecord>>(strJsonRecords);
List<OrderTally> lstOrderTally = lstOrderRecord.GroupBy(d => d.OrdNo)
.Select(g => new OrderTally
{
OrdNo = g.Key.ToString(),
TotalOrdQty = g.Sum(s => s.OrdQty).ToString(),
}).ToList();
string strJsonResult = JsonConvert.SerializeObject(lstOrderTally, Formatting.Indented);
return strJsonResult;
}
}

您可以通过以下代码来实现它。

string strJsonResult = JsonUtils.GetJsonOfOrderTally(strJsonRecords);

然后,您将得到以下结果。

[
{
"Ord No": "41035",
"Total Ord Qty": "7"
},
{
"Ord No": "41034",
"Total Ord Qty": "46"
}
]

最新更新