Coder Perfect

In C#, convert a list to a string.

Problem

In C#, how do I convert a list to a string?

When I use toString on a List object, I get the following:

Asked by IAdapter

Solution #1

Perhaps you’re attempting to do something.

string combinedString = string.Join( ",", myList.ToArray() );

You can replace “,” with whatever you want to use to divide the list’s items.

You could also do what was mentioned in the comments.

string combinedString = string.Join( ",", myList);

Reference:

Join<T>(String, IEnumerable<T>) 
Concatenates the members of a collection, using the specified separator between each member.

Answered by Øyvind Bråthen

Solution #2

I’m going to trust my instincts and presume you want to concatenate the results of using ToString on each list entry.

var result = string.Join(",", list.ToArray());

Answered by ChaosPandion

Solution #3

String is an option. Join:

List<string> list = new List<string>()
{
    "Red",
    "Blue",
    "Green"
};

string output = string.Join(Environment.NewLine, list.ToArray());    
Console.Write(output);

The following is the end result:

Red    
Blue    
Green

You can replace Environment.NewLine with a string-based line-separator of your choice as an alternative.

Answered by eandersson

Solution #4

String.Join(” “, myList) or String.Join(” “, myList.ToArray()) are two ways to join strings. The separator between the substrings is the first argument.

var myList = new List<String> { "foo","bar","baz"};
Console.WriteLine(String.Join("-", myList)); // prints "foo-bar-baz"

You may need to use ToArray() on the list first, depending on your.NET version.

Answered by Markus Johnsson

Solution #5

You can use LINQ to create something significantly more sophisticated than a simple join, for example.

var result = myList.Aggregate((total, part) => total + "(" + part.ToLower() + ")");

Will accept [“A,” “B,” and “C”] and you’ll get “(a)(b)(c)”

Answered by James Gaunt

Post is based on https://stackoverflow.com/questions/4981390/convert-a-list-to-a-string-in-c-sharp