0

Is there a simpler way of converting a two dimensional array in C#, such as [[1, 2, 3],[4, 5, 6]] into a string that says "[[1, 2, 3],[4, 5, 6]]", other than incrementing through each value and adding in the syntax manually?

I would like to use the array as an argument in my webView.ExecuteJavascript() method, which takes the method name string as an argument. Ideally, in C#, it would look like

webView.ExecuteJavascript("updateValues([[1, 2, 3],[4, 5, 6]])")

The updateValues function in javascript looks like this

updateValues(newvalues) {
oldvalues = newvalues
}

Would there be an easier way to do this? Right now, the results are stored in a list of double arrays (List), and calling .ToArray().ToString(), in a form such as this:

webView.ExecuteJavascript("updateValues(" + gaugeCol.ToArray().ToString() + ")");

only gives me the variable type and not the actual values.

Thanks

1
  • if you are asking about a recommendation for a library then this is out of scope for this site. as you know, there is no other way than going through each element and converting them to strings. Commented Jul 14, 2014 at 22:08

2 Answers 2

4

You can use JavaScriptSerializer

var arr = new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } };
string json = new JavaScriptSerializer().Serialize(arr); 

or Json.Net

string json = JsonConvert.SerializeObject(arr);

That way, you can convert almost any kind of object to json, not only arrays...

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

Comments

1

You can use an expression like this to turn the list of arrays into the Javascript syntax:

"[" + String.Join(",", gaugeCol.Select(g =>
  "[" + String.Join(",", Array.ConvertAll(g, Convert.ToString)) + "]"
)) + "]"

2 Comments

I am curious why it was down-voted. What, this code does not produce the desired result?
@akonsu: I'm curious too. The code is tested, and does produce exactly the desired result.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.