3

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?

2
  • 1
    Maybe you could use a Dictionary<long, int> or Dictionary<string, string> Commented Nov 17, 2016 at 19:14
  • What you show is not a 2D array, but a jagged array (an array of arrays). Commented Nov 17, 2016 at 21:07

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

this line shows syntax error - string test = string.Join(Environment.NewLine, cptarray .Select((line, index) => $"cptarray[{index}] = {string.Join(", ", line.Select(item => "\"" + item + "\""))}"));
@Aruna: do you use C# 6.0? $"..." is a string interpolation which appears in C# 6.0
@Aruna: I've changed string interpolation for string formatting in the test (see my edit)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.