Mohanapriya R Mohanapriya R
Updated date Jun 13, 2024
In this article, we will learn how to convert arrays to strings in C#. We will convert using the methods like "string.Join," "StringBuilder," and "LINQ."

Method 1: Using string.Join()

This string.Join() method concatenates all the elements of an array into a single string, separated by a specified delimiter.

using System;

class Program
{
    static void Main()
    {
        // Example array
        int[] numbers = { 1, 2, 3, 4, 5 };

        // Convert array to string using string.Join
        string result = string.Join(", ", numbers);

        // Output the result
        Console.WriteLine(result);
    }
}

Output:

1, 2, 3, 4, 5

Method 2: Using StringBuilder

For complex arrays, we are using StringBuilder. This class provides mutable strings and allows for easy concatenation.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        // Example array
        char[] characters = { 'A', 'B', 'C', 'D', 'E' };

        // Convert array to string using StringBuilder
        StringBuilder sb = new StringBuilder();
        foreach (char c in characters)
        {
            sb.Append(c);
        }
        string result = sb.ToString();

        // Output the result
        Console.WriteLine(result);
    }
}

Output:

ABCDE

Method 3: Using ToArray() and ToString()

We will also use the LINQ extension method ToArray() in combination with ToString() to convert elements of the array to a string.

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // Example array
        double[] prices = { 100.99, 230.45, 70.89, 150.67 };

        // Convert array to string using LINQ and ToString
        string result = string.Join(", ", prices.Select(p => p.ToString()));

        // Output the result
        Console.WriteLine(result);
    }
}

Output:

100.99, 230.45, 70.89, 150.67

Comments (0)

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