Convert var List to string c#

  1. HowTo
  2. C# Howtos
  3. Convert List to String in C#

Convert List to String in C#

Csharp Csharp List Csharp String

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:

Ross, Joey, Chandler

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

using System; using System.Collections.Generic; namespace list_to_string { class Program { static void Main[string[] args] { List names = new List[] { "Ross", "Joey", "Chandler" }; string joinedNames = String.Join[", ", names.ToArray[]]; Console.WriteLine[joinedNames]; } } }

Output:

Ross, Joey, Chandler

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 String.Join[] function in C#.

This method is much faster and is preferable to the previous method.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp List

  • Add List to Another List in C#
  • Shuffle a List in C#

    Related Article - Csharp String

  • Generate Random Alphanumeric Strings in C#
  • Add List to Another List in C#
    • Convert Array to List in C#
    • Convert Stream to Byte Array in C#
    report this ad

    Video liên quan

    Chủ Đề