2

I'm new to C#, and apologies for the noob question - I'm trying to convert a list of strings to a single string so I can use it with WWWForm's POST function.

If I have a list of strings (e.g. kidIds = ["a#123", "b#123"]), how do I easily convert it to a single string ("a#123, b#123")? In Javascript, I would simply do kidIds.join(","), but I'm not sure how to do it in C#.

I tried doing kidIds.ToArray().ToString(), but it's not really giving me what I want. I could loop through the entire list using a for loop, but I was wondering if there's a simpler one liner I could use?

Dan Tang
  • 1,273
  • 2
  • 20
  • 35

5 Answers5

7

Since you are new to C# I would like to tell you that, you were trying to convert a list of strings to a single string. No it is not a list of string but it is a array of string. List of strings would be initalize like

List<string> SomeName = new List<string>();

Where as your one is declared as array. Now you can Join the Array of strings into one string as same as Javascript like

string SomeString = String.Join(",", kidIds);

The string.Join method combines many strings into one. It receives two arguments: an array (or IEnumerable) and a separator string.

You can also create one string out of the String array using + that would concatenate the strings like

string smstr = String.Empty;
for(int i=0; i<kidIds.Length; i++)
{
    smstr = smstr + kidIds[i];
    //or
    smstr += kidIds[i]
}

You can also choose StringBuilder to create one string out of array of strings since StringBuilder.Append() method is much better than using the + operator like

StringBuilder sb = new StringBuilder();
for(int i=0;i<kidIds.Length;i++)
{
    sb.Append(kidIds[i]);
}

But StringBuilder is good when the concatenations are less than 1000, String.Join() is even more efficient than StringBuilder.

Mohit S
  • 13,723
  • 6
  • 34
  • 69
6

There is basically the same thing as JavaScript's join()

String.Join Method

shole
  • 4,046
  • 2
  • 29
  • 69
4

Use String.Join(',', kidIds);

https://msdn.microsoft.com/en-us/library/tk0xe5h0(v=vs.110).aspx

Z .
  • 12,657
  • 1
  • 31
  • 56
  • This should be the accepted answer! Thanks a lot, I knew there was a oneliner for that. Except I had to use `string.Join(",", kidIds)` since it expected a `string` not a `char` as first parameter. – derHugo Oct 23 '18 at 07:12
2

Perhaps you can try the function concat, like

String str = "";

str = kidIds[0] + kidIds[1];

or

str = str.concat(kidIds[0], kidIds[0]);

or

for(int i=0;i<length;i++)
{
    str += kidIds[i];
}

I think i would help.

Jeffrey Cheong
  • 348
  • 3
  • 13
1

You can do this using following code...

 string[] kidIds = { "a#123", "b#123" };

        String str = "";

        foreach (var kidId in kidIds)
        {
            str += kidId + ",";
        }

        str = str.Remove(str.Length - 1,1); // this line use for remove last comma

thanks...

Thili77
  • 1,061
  • 12
  • 20