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

基于JSON内条件统计符合要求的年龄数量的实现问题

实现符合条件的年龄数量统计方法

核心思路

给定的JSON中data字段是非结构化文本字符串,而非标准JSON结构,因此无法直接通过模型反序列化或JObject直接访问age属性。需要先提取该字符串,再从中解析所有age值,最后统计符合age >= 50的数量。

具体实现代码(.NET Core/.NET 5+)

using System;
using System.Text.Json;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string jsonString = """{"data":"key = IAfpK, age = 58, key = WNVdi, age = 64"}""";
        
        // 解析JSON提取data字段内容
        using var jsonDoc = JsonDocument.Parse(jsonString);
        string dataContent = jsonDoc.RootElement.GetProperty("data").GetString();
        
        // 正则匹配所有age数值
        var ageMatches = Regex.Matches(dataContent, @"age = (\d+)");
        
        // 统计符合条件的年龄数量
        int qualifiedCount = ageMatches.Cast<Match>()
                                       .Select(m => int.Parse(m.Groups[1].Value))
                                       .Where(age => age >= 50)
                                       .Count();
        
        Console.WriteLine(qualifiedCount); // 输出:2
    }
}

步骤说明

  • 解析JSON:使用JsonDocument高效解析JSON,直接提取data字段的文本内容,无需定义额外模型。
  • 提取age值:通过正则表达式@"age = (\d+)"匹配所有age相关条目,精准捕获数字部分。
  • 统计符合条件的数量:将捕获的字符串转为整数,筛选出大于等于50的数值,最终统计数量。

.NET Framework兼容方案

若使用.NET Framework,可借助Newtonsoft.Json解析JSON,核心逻辑一致:

using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string jsonString = """{"data":"key = IAfpK, age = 58, key = WNVdi, age = 64"}""";
        
        JObject jsonObj = JObject.Parse(jsonString);
        string dataContent = jsonObj["data"].ToString();
        
        var ageMatches = Regex.Matches(dataContent, @"age = (\d+)");
        
        int qualifiedCount = ageMatches.Cast<Match>()
                                       .Select(m => int.Parse(m.Groups[1].Value))
                                       .Where(age => age >= 50)
                                       .Count();
        
        Console.WriteLine(qualifiedCount); // 输出:2
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:03:34