TechieClues TechieClues
Updated date Jan 10, 2023
In this blog, we will learn how to convert a list of strings into a single string in C#

We can easily convert a list of strings into a single string in C# using below methods.

Using 'String.Join':

The String.Join method is used to concatenate each element in a list to a single string in C#. The Join method takes a separator to be applied between each element in the returned string.

The below example indicates this:

using System;
using System.Collections.Generic;
 
public class ConvertListToString
{
    public static void Main()
    {
        List<string> cars = new List<string>() { "BMW", "Toyota", "Mazda", "Audi"};
 
        string carStr = String.Join(", ", cars);
 
        Console.WriteLine(carStr );

        Console.ReadKey();
    }
}

 Output:

BMW, Toyota, Mazda, Audi

Using Linq:

We will also use Linq to convert a list of strings into a single string as shown below. An aggregate method is used for an accumulator function over a sequence. This method will work with System.Collections.Generic.IEnumerable collection.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConvertListToString
{
    class Program
    {
        public static void Main()
        {
            List<string> cars = new List<string>() { "BMW", "Toyota", "Mazda", "Audi" };

            string carStr = cars.Aggregate("", (cur, c) => cur + (c + ","));

            Console.WriteLine(carStr);

            Console.ReadKey();
        }
    }
}

  Output:

BMW, Toyota, Mazda, Audi

 

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!