C# - How to write a List<List<string>> to CSV file?

10,565

Solution 1

List<List<String>> dataList = new List<List<string>>();
//...
const char SEPARATOR = ",";
using (StreamWriter writer = new StreamWriter("file.csv"))
{
    dataList.ForEach(line =>
    {
        var lineArray = line.Select(c =>
            c.Contains(SEPARATOR) ? c.Replace(SEPARATOR.ToString(), "\\" + SEPARATOR) : c).ToArray();
        writer.WriteLine(string.Join(SEPARATOR, lineArray));
    });
}

Solution 2

CSV format by itself does not intend to be formatted with rows with variable columns length. CSV (Comma separated values) is just "table like" format, so if you want to follow its convention, you have to first define all possible columns and fill rows one-by-one, so several cells on several rows will remain empty.

If this is not what you want, just choose your custom format.

Share:
10,565
Whatever
Author by

Whatever

Updated on June 04, 2022

Comments

  • Whatever
    Whatever almost 2 years

    I'd like to write some data to a CSV file using C#.

    Here's my code at the moment :

    int length = readData.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Length;
    
    List<List<string>> dataList = new List<List<string>>();
    
    foreach (string line in readData.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
    {
        List<string> partsLine = new List<string>();
        partsLine.AddRange(line.Split('\t'));
        dataList.Add(partsLine);
    }          
    

    So, I'm splitting all the data in lines.

    Then I split each line with '\t' separator, and add each part of the line in a list.

    And at the end I have a list containing all the lists of split lines.

    So the list looks like :

    • List1 {txt1, txt 2} = first line
    • List2 {txt3, txt 4, txt 5, txt 6} = second line
    • List3 {txt7, txt 8, txt 9, txt 10} = third line
    • List4 {txt 11, txt 12} etc.

    All of the lists don't have the same lenght as you can see.

    What I'd like to do is writing all the lists to a CSV file.

    Each list would fill a row and a certain number of columns, depending of the lenght of the list (i.e. txt1 should be (row1, col1), txt2 should be (row1, col2), txt3 should be (row2, col1), txt4 would be (row2, col2)...).

    How can I do that ?

    Thanks