Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list to a string in C#

Tags:

string

c#

.net

list

People also ask

Can I convert a list to a String?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I convert a String to a list of strings?

How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.

Can we convert list to object?

In short, to convert an ArrayList to Object array you should: Create a new ArrayList. Populate the arrayList with elements, using add(E e ) API method of ArrayList. Use toArray() API method of ArrayList.


Maybe you are trying to do

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

You can replace "," with what you want to split the elements in the list by.

Edit: As mention in the comments you could also do

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

Reference:

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

I am going to go with my gut feeling and assume you want to concatenate the result of calling ToString on each element of the list.

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

You could use string.Join:

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

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

The result would be:

Red    
Blue    
Green

As an alternative to Environment.NewLine, you can replace it with a string based line-separator of your choosing.


If you want something slightly more complex than a simple join you can use LINQ e.g.

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

Will take ["A", "B", "C"] and produce "(a)(b)(c)"