Sabari M Sabari M
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

Sabari M
Sabari M
Software Professional, India

IT professional with 15+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

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