- HowTo
- C# Howtos
- Convert List to String in C#
Convert List to String in C#
Created: March-13, 2021 | Updated: March-21, 2021
In this tutorial, we will discuss methods to convert a List to a string variable in C#.
Convert List to String With the Linq Method in C
The Linq or language integrated query can perform robust text manipulation in C#. The Linq has an Aggregate[] function that can convert a list of strings to a string variable. The following code example shows us how to convert a List to a string with the Linq method in C#.
using System; using System.Collections.Generic; using System.Linq; namespace list_to_string { class Program { static void Main[string[] args] { List names = new List[] { "Ross", "Joey", "Chandler" }; string joinedNames = names.Aggregate[[x, y] => x + ", " + y]; Console.WriteLine[joinedNames]; } } }Output:
We create the list of strings names and insert the values { "Ross", "Joey", "Chandler" } in the names. Then we join the strings inside the names list with the , as the separator between them using the Aggregate[] function in C#.
This method is very slow and is not recommended. It is the same as running a foreach loop and concatenating each element.
Convert List to String With the String.Join[] Function in C
The String.Join[separator, Strings] function can concatenate the Strings with the specified separator in C#. The String.Join[] function returns a string formed by joining the Strings parameter with the specified separator.
The following code example shows us how we can convert a List to a string with the String.Join[] function in C#.
Output:
Ross, Joey, ChandlerWe create the list of strings names and insert the values { "Ross", "Joey", "Chandler" } in the names. Then we join the strings inside the names list with the , as the separator between them using the String.Join[] function in C#.
This method is much faster and is preferable to the previous method.
Related Article - Csharp List
Related Article - Csharp String
- Convert Array to List in C#
- Convert Stream to Byte Array in C#