Aruna - 1 year ago 86
C# Question

Two Dimentional Array C#

I will get the input from the user like this - "99211,99212,99213_1,99214,99215_3" and I store it in a string as

``````string cpt = "99211,99212,99213_1,99214,99215_3";
cptarray = cpt.Split(',');
``````

I got the output as

``````cptarray[0] = "99211"
cptarray[1] = "99212"
cptarray[2] = "99213_1"
cptarray[3] = "99214"
cptarray[4] = "99215_3"
``````

But I would like the output to be:

``````cptarray[0][0] = "99211",""
cptarray[1][0] = "99212",""
cptarray[2][0] = "99213","1"
cptarray[3][0] = "99214",""
cptarray[4][0] = "99215","3"
``````

If I need to get the output like above then can I use the 2D array, is it the correct approach? Can anyone shed some light on this?

According to the syntax provided:

`````` cptarray[0][0]
...
cptarray[4][0]
``````

you want a jagged array, not 2D one; you can construct this array with a help of Linq:

`````` var cptarray = cpt
.Split(',')
.Select(number => number.Split('_'))
.Select(items => items.Length == 1 ? new string[] {items[0], ""} : items)
.ToArray();
``````

Test

``````string test = string.Join(Environment.NewLine, cptarray
.Select((line, index) => string.Format("cptarray[{0}] = {1}",
index,
string.Join(", ", line.Select(item => "\"" + item + "\"")))));

Console.Write(test);
``````

Output

`````` cptarray[0] = "99211", ""
cptarray[1] = "99212", ""
cptarray[2] = "99213", "1"
cptarray[3] = "99214", ""
cptarray[4] = "99215", "3"
``````