Mohanapriya R Mohanapriya R
Updated date May 05, 2024
In this article, we will learn how to convert lists to strings in C#.

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)

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