Method 1: Using String.Join()
This method takes an array or IEnumerable<T> and concatenates its elements into a single string, separated by a specified delimiter.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
string fruitsString = String.Join(", ", fruits);
Console.WriteLine(fruitsString);
}
}
Output:
Apple, Banana, Orange
Method 2: Using a Loop
Another method is to iterate over the elements of the list and concatenate them into a string manually. While this method gives you more control over the formatting of the resulting string, it requires writing more code.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
string fruitsString = "";
foreach (string fruit in fruits)
{
fruitsString += fruit + ", ";
}
fruitsString = fruitsString.TrimEnd(',', ' ');
Console.WriteLine(fruitsString);
}
}
Output:
Apple, Banana, Orange
Comments (0)