62
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?

Sam
  • 7,252
  • 16
  • 46
  • 65
user2869820
  • 747
  • 3
  • 7
  • 13
  • Possible duplicate of [Creating a comma separated list from IList or IEnumerable](https://stackoverflow.com/questions/799446/creating-a-comma-separated-list-from-iliststring-or-ienumerablestring) – Binke Jul 17 '19 at 12:18

6 Answers6

145
string Something = string.Join(",", MyList);
ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
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"

MUG4N
  • 19,377
  • 11
  • 56
  • 83
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).

Sam
  • 7,252
  • 16
  • 46
  • 65
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.

Falgantil
  • 1,290
  • 12
  • 27
  • 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? – Wouter Vanherck May 27 '20 at 09:17
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>();
Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116
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())
modle13
  • 1,242
  • 2
  • 16
  • 16
  • This shouldn't have happened as [string.Join](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-5.0#System_String_Join_System_String_System_Collections_Generic_IEnumerable_System_String__) works on `IEnumerable`s, which both `List` and `Array` are. – Bip901 Dec 20 '20 at 16:52