Reputation: 847
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
?
Upvotes: 72
Views: 203319
Reputation: 1378
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())
Upvotes: 1
Reputation: 7398
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).
Upvotes: 7
Reputation: 1310
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.
Upvotes: 7
Reputation: 9646
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>();
Upvotes: 6
Reputation: 19717
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"
Upvotes: 21