0

I need to convert Json string e.g. ["value1","value2","value3","value4"] into a array of Tuples such as,

Tuple<value1,value2> Tuple<value3,value4> 

I was thinking of converting the json string into string [] and then convert it to one Tuple at a time, but wondering if there is an easy way of doing it?

1
  • Thats a simple array. Use Take(2) method from Linq to create tuples Commented Jan 27, 2021 at 5:05

1 Answer 1

1

You can use Linq as shown below:

var jArrayString = "[\"value1\",\"value2\",\"value3\",\"value4\"]"; var jArray = JArray.Parse(jArrayString); var tuples = jArray.Select((j, index) => index % 2 == 0 ? new Tuple<string, string>(jArray[index].Value<string>(), jArray[index + 1].Value<string>()) : null) .Where(t => t != null); 

You can check the fiddle - https://dotnetfiddle.net/g1MFjb

Note - the above may not be a optimized way. the same can be done using a simple for loop :).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.