C# List to string
last modified January 19, 2024
In this article we show 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
method 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.
List<string> words = ["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.
using System.Text; List<string> words = ["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.
List<string> words = ["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.
List<string> words = ["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.)
Source
In this article we have showed how to convert a list to a string in C#.
Author
List all C# tutorials.