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

如何对存在event属性缺失的不一致JArray按event值统计数量?

如何安全统计JArray中event属性等于指定值的元素数量

你的问题在于部分JArray元素的attributes里并没有event字段,直接用(int)x["attributes"]["event"]会触发NullReferenceException。下面是几种安全可靠的实现方式:

方法一:使用空传播运算符进行存在性检查

这种方式简洁直观,通过空传播运算符?.避免空引用,先确认event字段存在再判断值:

var eventZeroCount = _ja
    .Select(x => x.ToObject<JObject>())
    .Where(item => 
        item["attributes"]?["event"] != null && 
        (int)item["attributes"]["event"] == 0)
    .Count();

方法二:利用GetValue方法处理缺失字段

GetValue<T>方法可以在字段不存在时返回默认值(这里用可空类型int?,缺失时返回null),代码更简洁:

var eventZeroCount = _ja
    .Select(item => item["attributes"] as JObject)
    .Where(attributes => attributes != null) // 先确保attributes对象存在
    .Count(attributes => attributes.GetValue<int?>("event") == 0);

方法三:循环遍历+TryGetValue(更严谨的类型检查)

如果需要额外验证event的类型是否为整数,避免非整数类型导致的转换错误,可以用这种方式:

int eventZeroCount = 0;
foreach (var item in _ja)
{
    // 先确认attributes是有效的JObject
    if (item["attributes"] is JObject attributes)
    {
        // 尝试获取event字段,并检查类型和值
        if (attributes.TryGetValue("event", out JToken eventToken) && 
            eventToken.Type == JTokenType.Integer && 
            (int)eventToken == 0)
        {
            eventZeroCount++;
        }
    }
}

以上三种方法都能安全地统计出event=0的元素数量,你可以根据自己的代码风格和需求选择合适的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:32:53