73
List<string> MyList = (List<string>)Session["MyList"];

MyList contains values like: 12 34 55 23.

I tried using the code below, however the values disappear.

string Something = Convert.ToString(MyList);

I also need each value to be separated with a comma (",").

How can I convert List<string> Mylist to string?

1

6 Answers 6

167
string Something = string.Join(",", MyList);
Sign up to request clarification or add additional context in comments.

Comments

21

Try this code:

var list = new List<string> {"12", "13", "14"};
var result = string.Join(",", list);
Console.WriteLine(result);

The result is: "12,13,14"

Comments

7

Entirely alternatively you can use LINQ, and do as following:

string finalString = collection.Aggregate("", (current, s) => current + (s + ","));

However, for pure readability, I suggest using either the loop version, or the string.Join mechanism.

1 Comment

Could you elaborate on the syntax? Am I correct in assuming the first argument to be the return string, which will be concatenated with the second argument? What are the variables current and s exactly, current string and current value?
7

Or, if you're concerned about performance, you could use a loop,

var myList = new List<string> { "11", "22", "33" };
var myString = "";
var sb = new System.Text.StringBuilder();

foreach (string s in myList)
{
    sb.Append(s).Append(",");
}

myString = sb.Remove(sb.Length - 1, 1).ToString(); // Removes last ","

This Benchmark shows that using the above loop is ~16% faster than String.Join() (averaged over 3 runs).

Comments

6

You can make an extension method for this, so it will be also more readable:

public static class GenericListExtensions
{
    public static string ToString<T>(this IList<T> list)
    {
        return string.Join(",", list);
    }
}

And then you can:

string Something = MyList.ToString<string>();

Comments

1

I had to add an extra bit over the accepted answer. Without it, Unity threw this error:

cannot convert `System.Collections.Generic.List<string>' expression to type `string[]'

The solution was to use .ToArray()

List<int> stringNums = new List<string>();
String.Join(",", stringNums.ToArray())

1 Comment

This shouldn't have happened as string.Join works on IEnumerables, which both List and Array are.

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.