简体   繁体   中英

Updating an Array of Object inside a Array of Object using linq in c#

I have a JSON object like below,

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

I have another Array of Strings of PartialBatchID's

["PAR1","PAR3"]

What would be the best and most quickiest way to update the status fields to Active for the PartialBatchID's present in above array, against the main json.

Here's a way using the Newtonsoft.Json Nuget package. Now in your example the PAR1 and PAR3 are already active, but this will work:

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'

          }
        ]
      }
    ]";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM