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

在C#中使用LINQ更新嵌套对象数组中的对象状态

C# LINQ批量更新JSON中指定PartialBatchID的Status字段

需求场景

现有如下JSON结构的批量数据:

[
  {
    "BatchId": "BAT1",
    "PartialBatch": [
      {
        "PartialBatchID": "PAR1",
        "Status": "Active"
      },
      {
        "PartialBatchID": "PAR2",
        "Status": "Inactive"
      }
    ]
  },
  {
    "BatchId": "BAT2",
    "PartialBatch": [
      {
        "PartialBatchID": "PAR3",
        "Status": "Active"
      },
      {
        "PartialBatchID": "PAR4",
        "Status": "Inactive"
      }
    ]
  }
]

以及需要更新的PartialBatchID数组:["PAR1","PAR3"],要求用LINQ以最快最优的方式将这些ID对应的Status字段设置为Active。

最优实现方案

1. 定义强类型实体类

先将JSON结构映射为C#强类型,保证类型安全和操作效率:

public class Batch
{
    public string BatchId { get; set; }
    public List<PartialBatch> PartialBatch { get; set; }
}

public class PartialBatch
{
    public string PartialBatchID { get; set; }
    public string Status { get; set; }
}

2. 核心处理逻辑

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json; // 若项目使用System.Text.Json,替换为对应命名空间

// 反序列化JSON到强类型集合
var rawJson = @"[
  {
    ""BatchId"": ""BAT1"",
    ""PartialBatch"": [
      {
        ""PartialBatchID"": ""PAR1"",
        ""Status"": ""Active""
      },
      {
        ""PartialBatchID"": ""PAR2"",
        ""Status"": ""Inactive""
      }
    ]
  },
  {
    ""BatchId"": ""BAT2"",
    ""PartialBatch"": [
      {
        ""PartialBatchID"": ""PAR3"",
        ""Status"": ""Active""
      },
      {
        ""PartialBatchID"": ""PAR4"",
        ""Status"": ""Inactive""
      }
    ]
  }
]";

var batches = JsonConvert.DeserializeObject<List<Batch>>(rawJson);

// 将目标ID存入HashSet,O(1)查找效率远高于List的O(n)
var targetPartialIds = new HashSet<string> { "PAR1", "PAR3" };

// 扁平化所有PartialBatch项,匹配目标ID后更新Status
batches.SelectMany(batch => batch.PartialBatch)
       .Where(partial => targetPartialIds.Contains(partial.PartialBatchID))
       .ToList() // 触发LINQ延迟执行,获取可操作的集合
       .ForEach(partial => partial.Status = "Active");

// 若需要输出更新后的JSON
var updatedJson = JsonConvert.SerializeObject(batches, Formatting.Indented);
Console.WriteLine(updatedJson);

3. 方案优势说明

  • 高效查找:用HashSet存储目标ID,查找时间复杂度为O(1),在目标ID数量较多时优势明显
  • 扁平化遍历:SelectMany直接将嵌套的PartialBatch集合扁平化,避免多层嵌套循环,代码简洁且执行高效
  • 延迟执行优化:通过ToList()触发LINQ查询的枚举,直接操作引用类型实体,避免重复遍历
  • 类型安全:强类型序列化比动态JSON操作(如JToken)更高效,同时避免运行时类型错误

若使用System.Text.Json替换Newtonsoft.Json

只需修改序列化/反序列化代码:

using System.Text.Json;

var batches = JsonSerializer.Deserialize<List<Batch>>(rawJson);
// ... 中间逻辑一致
var updatedJson = JsonSerializer.Serialize(batches, new JsonSerializerOptions { WriteIndented = true });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:10:24