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?

1

5 Answers 5

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.

6

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

String.Join Method

1
  • Thank you, this worked perfectly! Will accept answer after the 5 mins have elapsed.
    – Dan Tang
    Dec 29, 2016 at 3:44
4

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

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

1
  • 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, 2018 at 7: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.

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...

Not the answer you're looking for? Browse other questions tagged or ask your own question.