- Home /
Is there a way to convert a 2d generic list to a string in unityscript
I have some javascript code I'm trying to convert that takes a two dimensional array and uses a javascript join to turn it into a string then splits the string to turn it into a one dimensional array.
I'm converting this code to run on iphone in pragma strict so I'm using generic .net lists instead of javascript type arrays. Is there an equivalent of the javascript type of join for generic lists or maybe another way to do this.
A list like this [3,4],[1,2],[5,6]. I would like to convert it into 3,4,1,2,5,6 a flat array of ints. The javascript code I'm trying to convert used array.join to convert it to a string, then it split the string thus creating the final array.
Is this list or array? How is it declared? Because you wrote about generic list and this what you posted looks like standard 2-dimensional array.
I created a generic list of lists of integers then populated it using a for loop and Add. The original code was in javascript from a webpage. I just wrote it that way to show the structure but it's in generic list format in unityscript. The comment section won't let me add code examples without messing up the format.
You can post a code in comments - just paste it and then select and press 101010 button. Or use Ctrl+$$anonymous$$
Answer by ArkaneX · Sep 13, 2013 at 07:24 PM
You can use String.Join to join string arrays into one string. If you have a generic list of strings, then you have to convert it to array before joining:
var list : List.<String> = new List.<String>();
list.Add("aaa");
list.Add("bbb");
list.Add("ccc");
var s = String.Join(",", list.ToArray());
If you want to convert generic list of non-string elements, then you have to cast them to strings first:
var list : List.<int> = new List.<int>();
list.Add(55);
list.Add(2);
list.Add(777);
var stringList = list.Select(function(x) x.ToString());
var s = String.Join(",", stringList.ToArray());
Above examples require System.Collections.Generic and System.Linq namespaces, so you have to import these:
import System.Collections.Generic;
import System.Linq;
UPDATE: after info from comments - you should be able to get flattened list from your variable using
var flattenedArray = list.SelectMany(function(x) x).ToArray();
where list is your generic list.
Thanks so much for your thorough answer. I think this will do the trick.