在C#中使用linq更新Object数组中的Object数组

e3bfsja2  于 2022-12-06  发布在  C#
关注(0)|答案(1)|浏览(148)

我有一个如下所示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"]

针对主json,将上述数组中存在的PartialBatchID的状态字段更新为“活动”的最佳和最快方法是什么?

hrirmatl

hrirmatl1#

下面是使用Newtonsoft.Json Nuget包的一种方法。现在在你的例子中PAR1和PAR3已经激活了,但这是可行的:

void Main()
{
    var match = new [] { "PAR1", "PAR3"};

    var json = JsonConvert.DeserializeObject<JsonData[]>(main);
    
    foreach (var b in json.SelectMany(x => x.PartialBatch).Where(x => match.Contains(x.PartialBatchID)))
    {
        b.Status = "Active";
    }
    
    var modifiedJson = JsonConvert.SerializeObject(json);
}

public class JsonData
{
    public string BatchId { get; set; }
    public Batch[] PartialBatch { get; set; }
}

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

const string main = @"
    [
      {
        'BatchId': 'BAT1',
        'PartialBatch': [
          {
            'PartialBatchID': 'PAR1',
            'Status': 'Active'
          },
          {
        'PartialBatchID': 'PAR2',
            'Status': 'Inactive'

          }
        ]
      },
      {
        'BatchId': 'BAT2',
        'PartialBatch': [
          {
            'PartialBatchID': 'PAR3',
            'Status': 'Active'
          },
          {
        'PartialBatchID': 'PAR4',
            'Status': 'Inactive'

          }
        ]
      }
    ]";

相关问题