How to combine/merge two JArrays in JSON.NET

前端 未结 4 1083
半阙折子戏
半阙折子戏 2021-01-04 02:38

I can\'t figure out how to concatenate two JArrays that I got be using JArray.Parse? The order of the arrays must be preserved i.e. the first array should be first and eleme

相关标签:
4条回答
  • 2021-01-04 02:48

    I used the Merge method, which modifies the original JArray:

     JArray test1 = JArray.Parse("[\"john\"]");
     JArray test2 = JArray.Parse("[\"doe\"]");
     test1.Merge(test2);
    
    0 讨论(0)
  • 2021-01-04 03:00

    My two cents for the generic case where you have n JArray's:

    IEnumerable<JArray> jarrays = ...
    var concatenated = new JArray(jarrays.SelectMany(arr => arr));
    

    And to project this onto the original question with two JArray's:

    JArray jarr0 = ...
    JArray jarr1 = ...
    var concatenated = new JArray(new[] { jarr0, jarr1 }.SelectMany(arr => arr));
    
    0 讨论(0)
  • 2021-01-04 03:03

    You can add elements to one JArray by calling JArray.Add(element) where element comes from the second JArray. You'll need to loop over the second JArray to add all of these elements, but this will accomplish what you want:

    for(int i=0; i<jarrayTwo.Count; i++)
    {
        jarrayOne.Add(jarrayTwo[i]);
    }
    

    in the above example jarrayOne will now contain all of the first array's elements followed by the second array's elements in sequence. You can take a look through the JArray documentation for further details.

    0 讨论(0)
  • 2021-01-04 03:05

    You can also use the union method:

    JArray test1 = JArray.Parse("[\"john\"]");
    JArray test2 = JArray.Parse("[\"doe\"]");
    test1 = new JArray(test1.Union(test2));
    

    Now test1 is

    [
      "john",
      "doe"
    ]
    
    0 讨论(0)
提交回复
热议问题