[c#] Convert a list to a string in C#

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]

This question is related to c# .net string list

The answer is


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());

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();

This seems to work for me.

var combindedString = new string(list.ToArray());

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


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!!!!


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().


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.


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.


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


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() );

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..


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>