using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;

namespace ReadCsv
{
    public static class CsvTools
    {
        // Load a CSV file into an array of arrays of strings.
        public static string[][] LoadCsv(string filename)
        {
            // Get the file's lines.
            string[] lines = File.ReadAllLines(filename);

            // Allocate the result array.
            int numRows = lines.Length;
            string[][] values = new string[numRows][];

            // Load the values into the array.
            for (int r = 0; r < numRows; r++) values[r] = lines[r].Split(',');

            // Return the values.
            return values;
        }

        // Return a string containing the data in CSV format.
        public static string ArrayToCsv(string[][] values)
        {
            // Make a StringBuilder to hold the data.
            StringBuilder sb = new StringBuilder();

            // Use string.Join to make each row into a CSV string.
            for (int r = 0; r <= values.GetUpperBound(0); r++)
                sb.AppendLine(string.Join(",", values[r]));

            // Remove the trailing newline and return the result.
            return sb.ToString().TrimEnd();
        }

        // An extension method to convert a string[][] into a CSV string.
        public static string ToCsv(this string[][] values)
        {
            return ArrayToCsv(values);
        }
    }
}
