64
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

151
string Something = string.Join(",", MyList);
20

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"

8

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
  • 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? May 27, 2020 at 9:17
8

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

0
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>();
2

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
  • This shouldn't have happened as string.Join works on IEnumerables, which both List and Array are.
    – Bip901
    Dec 20, 2020 at 16:52

Your Answer

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

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