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
Comments (0)