You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中通过Linq处理JSON以检测成分占比总和错误

问题描述

需要检测JSON数据中所有compo_groups的perc字段总和是否恰好为100%。示例中第一组总和100%合规,第二组总和150%存在错误。需要用C#实现该检测,但不清楚如何将JSON转换为可通过LINQ处理的集合。

JSON示例:

{
  "data": "014",
  "theme": "COLORADO CASUAL",
  "family": "2163",
  "category": "00",
  "compo_groups": [
    {
      "title": "HEAD024",
      "values": [
        {
          "perc": "100",
          "desc": "COMP036"
        }
      ]
    },
    {
      "title": "HEAD035",
      "values": [
        {
          "perc": "100",
          "desc": "COMP042"
        },
        {
          "perc": "50",
          "desc": "COMP043"
        }
      ]
    }
  ],
  "product_name": "D812",
  "supplier_code": "1011"
}

解决方案

1. 定义匹配的C#模型类

根据JSON结构创建实体类,序列化后就能得到可操作的对象集合:

public class ProductData
{
    public string data { get; set; }
    public string theme { get; set; }
    public string family { get; set; }
    public string category { get; set; }
    public List<CompoGroup> compo_groups { get; set; }
    public string product_name { get; set; }
    public string supplier_code { get; set; }
}

public class CompoGroup
{
    public string title { get; set; }
    public List<CompoValue> values { get; set; }
}

public class CompoValue
{
    public string perc { get; set; }
    public string desc { get; set; }
}

2. 将JSON解析为C#对象

可以选择两种主流的JSON序列化库:

方式一:使用Newtonsoft.Json(需先安装NuGet包)

using Newtonsoft.Json;

// jsonString为你的JSON原始字符串
var productData = JsonConvert.DeserializeObject<ProductData>(jsonString);

方式二:使用.NET内置的System.Text.Json

using System.Text.Json;

var productData = JsonSerializer.Deserialize<ProductData>(jsonString);

3. 用LINQ检测占比总和

遍历每个成分组,计算perc的总和并校验是否等于100:

// 筛选出不符合要求的成分组
var invalidGroups = productData.compo_groups
    .Select(group => new 
    {
        GroupTitle = group.title,
        TotalPerc = group.values.Sum(v => int.Parse(v.perc))
    })
    .Where(result => result.TotalPerc != 100)
    .ToList();

// 输出错误信息
foreach (var group in invalidGroups)
{
    Console.WriteLine($"成分组 {group.GroupTitle} 占比总和为 {group.TotalPerc}%,不符合100%要求");
}

额外提示

如果JSON中perc可能为空或非数字,建议添加异常处理避免崩溃:

TotalPerc = group.values.Sum(v => 
{
    if (int.TryParse(v.perc, out int percValue))
        return percValue;
    return 0; // 可根据业务需求调整无效值的处理逻辑
})

内容的提问来源于stack exchange,提问作者Bastien Vandamme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 17:55:42