ZetCode

C# List to string

last modified July 9, 2021

C# List to string tutorial shows how to convert a List to a string in C#.

To turn a list of elements into a single string in C#, we will utilize the string.Join method, StringBuilder object, Enumerable.Aggregate method and the string concatenation operator.

The string.Join metho concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. The StringBuilder class is used to dynamically build strings. The Enumerable.Aggregate method applies an accumulator function over a sequence of values.

C# uses the + operator to concatenate strings.

C# List to string example

In the following example, we transform a list to a string with the string.Join method.

Program.cs
using System;
using System.Collections.Generic;

var words = new List<string> {"a", "visit", "to", "London"};
var res = string.Join("-", words);

Console.WriteLine(res);

In the example, we create a slug from a list of words.

$ dotnet run
a-visit-to-London

C# List to string example II

In the second example, we use the StringBuilder class.

Program.cs
using System;
using System.Text;
using System.Collections.Generic;

var words = new List<string> {"There", "are", "three", "chairs", "and", "two", 
    "lamps", "in",  "the", "room"};

var builder = new StringBuilder();

foreach (var word in words) 
{
    builder.Append(word).Append(" ");
}

Console.WriteLine(builder.ToString());

We go through the list in a foreach loop and dynamically build the string with the StringBuilder's Append method. The ToString method converts the StringBuilder object to a string.

$ dotnet run
There are three chairs and two lamps in the room

C# List to string example III

The next example uses the Enumerable.Aggregate method.

Program.cs
using System;
using System.Linq;
using System.Collections.Generic;

var words = new List<string> {"There", "are", "three", "chairs", "and", "two", 
    "lamps", "in",  "the", "room"};

var res = words.Aggregate((total, part) => $"{total} {part}");
Console.WriteLine(res);

The example uses the string interpolation operation in the accumulator function.

C# List to string example IV

Finally, we build the string with the string concatenation operation.

Program.cs
using System;
using System.Collections.Generic;

var words = new List<string> {"There", "are", "three", "chairs", "and", "two", 
    "lamps", "in",  "the", "room"};

string res = string.Empty;

words.ForEach(word => {

    res += $"{word} ";
});

Console.WriteLine(res);

We go through all the elements of the list with the ForEach method. We build the string using the string concatenation operator. (In our case the += compound operator.)

In this tutorial, we have showed how to convert a list to a string in C#.

Read C# tutorial or list all C# tutorials.