Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
67 views
in Technique[技术] by (71.8m points)

c# - Json string to Array of Tuples

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?

question from:https://stackoverflow.com/questions/65912939/json-string-to-array-of-tuples

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...