How to merge / merge two JArrays in JSON.NET

I can't figure out how to combine the two JArrays that I used using JArray.Parse? The order of the arrays must be preserved, i.e. The first array should be the first, and the element in seconds should appear later.

+4
source share
4 answers

You can add elements to one JArray by calling JArray.Add(element) , where the element comes from the second JArray. You will need to iterate over the second JArray to add all 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 the first elements of the array, followed by subsequent elements of the array. More information can be found in JArray .

+7
source

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

  JArray test1 = JArray.Parse("[\"john\"]"); JArray test2 = JArray.Parse("[\"doe\"]"); test1.Merge(test2); 
+8
source

You can also use union method:

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

Now test1 is

 [ "john", "doe" ] 
+6
source

My two cents for the general case when you have n JArray 's:

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

And project this onto the original question using two JArray :

 JArray jarr0 = ... JArray jarr1 = ... var concatenated = new JArray(new[] { jarr0, jarr1 }.SelectMany(arr => arr)); 
0
source

Source: https://habr.com/ru/post/1468822/


All Articles