-1

I have two arrays (that are always going to have the same length). Something like

array1 = [ "a", "b", "c" ]  
array2 = [ 1, 2, 3 ]

I'd like to know if there's a way to merge both arrays into a single JSON object in C# to something like

{
"a": 1,
"b": 2,
"c": 3
}

any help is appreciated.

mercy
  • 11
  • 1
  • 2
  • 3
    [Zip](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip?view=net-6.0) + [ToDictionary](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.todictionary?view=net-6.0) then json serialization ? (Writing something a little more complete and testing before posting as an answer) – Irwene Oct 21 '22 at 13:47
  • 2
    And please for your next question try to include at least one example of what you have tried to implement [how do I ask a good question](https://stackoverflow.com/help/how-to-ask) – Irwene Oct 21 '22 at 13:59

1 Answers1

4

It was that simple: Zip + ToDictionary before serialization.

using System.Text.Json;
using System.Text.Json.Serialization;

var array1 = new string[]{ "a", "b", "c" } ;
var array2 = new int[] { 1, 2, 3 };

var dict = array1
    .Zip(array2, (a1,a2)=> (key:a1, value:a2))
    .ToDictionary(k => k.key, v => v.value);

Console.WriteLine(JsonSerializer.Serialize(dict));

Zip takes two collections of the same size and creates a new one based on the result of a merge function (here, I used it to create tuples)

ToDictionary creates an enumerable to a dictionary structure.

Outputs:

{"a":1,"b":2,"c":3}

One note about this answer though: If you have two or more identical items in the first collection, this WILL throw an exception.

Irwene
  • 2,807
  • 23
  • 48