user2869820
user2869820

Reputation: 847

Convert a list of strings to a single string

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

Answers (6)

modle13
modle13

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

Sam
Sam

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

Falgantil
Falgantil

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

Misha Zaslavsky
Misha Zaslavsky

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

MUG4N
MUG4N

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

ProgramFOX
ProgramFOX

Reputation: 6390

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

Upvotes: 166

Related Questions