297

How do I convert a list to a string in C#?

When I execute toString on a List object, I get:

System.Collections.Generic.List`1[System.String]

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
IAdapter
  • 62,595
  • 73
  • 179
  • 242
  • 1
    A List is a collection, what is this string supposed to look like? – Marko Feb 12 '11 at 23:45
  • You can try any of the three ways mentioned [here](https://stackoverflow.com/a/33142321/465053). – RBT Aug 08 '17 at 12:46
  • 2
    @Marko like in java? `["element1","element2"]` – Niton Feb 11 '21 at 22:05
  • @Niton: What Marko is trying to saying is that there is a bit of ambiguity about what a List string is supposed to look like. In the example you gave, all the items look like strings. However, lists can also be made of objects, which may or may not have their own toString functions. I found this question by searching for the very same thing. – MXMLLN Feb 04 '23 at 10:42

14 Answers14

569

Maybe you are trying to do

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

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

Edit: As mentioned in the comments you could also do

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

Reference:

Join<T>(String, IEnumerable<T>) 
Concatenates the members of a collection, using the specified separator between each member.
Parsa
  • 7,995
  • 2
  • 27
  • 37
Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
  • 5
    do you mean string combindedString = string.Join( ",", myList.ToArray()); – sawe Aug 07 '14 at 05:26
  • 2
    Argument '2': cannot convert from 'System.Collections.Generic.List' to 'string[]' – Ash Oct 28 '14 at 13:09
  • 10
    I used this recently, it works - just omit the .ToArray() – Adrian K Jul 03 '17 at 22:17
  • 3
    @AdrianK you are correct because the .Net 4.0 added the ability to pass in any IEnumerable. However 4.0 was released in April 2010, before this question and answer were posted so perhaps the folks here were just not yet aware of it (other than a few down below) – Andrew Steitz Sep 07 '17 at 21:06
  • For vb.net, Dim combindedString As String = String.Join(",", myList.ToArray()) – PartTimeNerd Jan 07 '19 at 05:13
62

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());
Shoban
  • 22,920
  • 8
  • 63
  • 107
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
24

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.

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
eandersson
  • 25,781
  • 8
  • 89
  • 110
15

String.Join(" ", myList) or String.Join(" ", myList.ToArray()). The first argument is the separator between the substrings.

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

Depending on your version of .NET you might need to use ToArray() on the list first..

Markus Johnsson
  • 3,949
  • 23
  • 30
14

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)"

James Gaunt
  • 14,631
  • 2
  • 39
  • 57
  • 1
    Use Aggregate with a seed as the first parameter to avoid throwing InvalidOperationException for empty collections. – Huacanacha Nov 25 '15 at 22:03
11

You have a List<string> - so if you want them concatenated, something like

string s = string.Join("", list);

would work (in .NET 4.0 at least). The first parameter is the delimiter. So you could also comma-delimit etc.

You might also want to look at using StringBuilder to do running concatenations, rather than forming a list.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
10

The .ToString() method for reference types usually resolves back to System.Object.ToString() unless you override it in a derived type (possibly using extension methods for the built-in types). The default behavior for this method is to output the name of the type on which it's called. So what you're seeing is expected behavior.

You could try something like string.Join(", ", myList.ToArray()); to achieve this. It's an extra step, but it could be put in an extension method on System.Collections.Generic.List<T> to make it a bit easier. Something like this:

public static class GenericListExtensions
{
    public static string ToString<T>(this IList<T> list)
    {
        return string.Join(", ", list);
    }
}

(Note that this is free-hand and untested code. I don't have a compiler handy at the moment. So you'll want to experiment with it a little.)

IAdapter
  • 62,595
  • 73
  • 179
  • 242
David
  • 208,112
  • 36
  • 198
  • 279
  • it does work when I call it not ToString or execute it with generic parameter. But I like your idea of using extension method :) – IAdapter Feb 13 '11 at 14:27
6

It's hard to tell, but perhaps you're looking for something like:

var myString = String.Join(String.Empty, myList.ToArray());

This will implicitly call the ToString() method on each of the items in the list and concatenate them.

Daniel Schaffer
  • 56,753
  • 31
  • 116
  • 165
3

This method helped me when trying to retrieve data from Text File and store it in Array then Assign it to a string avariable.

string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "\\Notes.txt");  
string marRes = string.Join(Environment.NewLine, lines.ToArray());

Hopefully may help Someone!!!!

PatsonLeaner
  • 1,230
  • 15
  • 26
3

If your list has fields/properties and you want to use a specific value (e.g. FirstName), then you can do this:

string combindedString = string.Join( ",", myList.Select(t=>t.FirstName).ToArray() );
2

The direct answer to your question is String.Join as others have mentioned.

However, if you need some manipulations, you can use Aggregate:

List<string> employees = new List<string>();
employees.Add("e1");
employees.Add("e2");
employees.Add("e3");

string employeesString = "'" + employees.Aggregate((x, y) => x + "','" + y) + "'";
Console.WriteLine(employeesString);
Console.ReadLine();
Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • 1
    in production code make sure your list have any element otherwise it will throw exception. – AZ_ Sep 30 '19 at 12:05
2

If you're looking to turn the items in a list into a big long string, do this: String.Join("", myList). Some older versions of the framework don't allow you to pass an IEnumerable as the second parameter, so you may need to convert your list to an array by calling .ToArray().

mattmc3
  • 17,595
  • 7
  • 83
  • 103
2

This seems to work for me.

var combindedString = new string(list.ToArray());
mutuma
  • 31
  • 3
-3
string strs="111,222,333"
string.Join(",",strs.Split(',').ToList().Select(x=>x.PadLeft(6,'0')).ToArray());

The output

000111,000222,000333
Peter Csala
  • 17,736
  • 16
  • 35
  • 75