0

I have some data in csv like

string[][] items = new string[][] {
  new string[] { "dog", "3" },
  new string[] { "cat", "2" },
  new string[] { "bird", "1" }
};

now I want to convert the input into properly formatted CSV lines and return them - expected output:

string[] csvLines = {"\"dog\";\"3\"", "\"cat\";\"2\"", "\"bird\";\"1\""};

or file:

"dog";"3"
"cat";"2"
"bird";"1"

what I've tried:

public static IEnumerable<string> GetCSVLines(string[][] list)
{
    using (MemoryStream stream = new MemoryStream())
    using (StreamWriter writer = new StreamWriter(stream))
    using (CsvHelper.CsvWriter csv = new CsvHelper.CsvWriter(writer))
    {
        foreach (var item in list)
        {
            foreach (var field in item)
            {
                csv.WriteField(field);
            }
            yield return csv.Record; //??
            csv.NextRecord();                  
        }                 
    }
}

Note: I can't just use string.Join() because the fields could contain ", delimiter ; or linebreaks.

14
  • What does that have to do with CsvHelper? A simple Select and String.Format will produce the output Commented Mar 28, 2019 at 13:06
  • You want the output to contain the escaped double quotes? Commented Mar 28, 2019 at 13:07
  • Your items array is clear ? Commented Mar 28, 2019 at 13:07
  • Why not just write list.Select(pair=>String.Format("\"{0}\";\"{1}\"",pair[0],pair[1])).ToArray() ? Commented Mar 28, 2019 at 13:08
  • 2
    @Toshi you'll have to explain what you're trying to do otherwise this question will be closed as unclear. I suspect you want to convert the input into properly formatted CSV lines and return them. That's not what the question asks though, the "desired output" has little to do with CSV lines Commented Mar 28, 2019 at 13:13

2 Answers 2

2

If you want to wrap items in quotations (with escapement: "ab\"c" should be "\"ab\"\"c\"") and Join them with ; you don't need CsvHelper but a simple Linq

  string[][] items = new string[][] {
    new string[] { "dog", "3" },
    new string[] { "cat", "2" },
    new string[] { "bird", "1" },
    new string[] { "e\"sc", "4" } // escapment demo
  };

  string[] result = items
    .Select(line => string.Join(";", 
       line.Select(item => "\"" + item.Replace("\"", "\"\"") + "\"")))
    .ToArray();

  Console.Write(string.Join(Environment.NewLine, result));

Outcome:

"dog";"3"
"cat";"2"
"bird";"1"
"e""sc";"4"
Sign up to request clarification or add additional context in comments.

Comments

1

I would say that @Dmitry Bychenko's answer is more straight forward, but if you did want to use CsvHelper it is possible.

public static IEnumerable<string> GetCSVLines(string[][] list)
{
    using (MemoryStream stream = new MemoryStream())
    using (StreamWriter writer = new StreamWriter(stream))
    using (CsvHelper.CsvWriter csv = new CsvHelper.CsvWriter(writer))
    using (StreamReader reader = new StreamReader(stream))
    {
        csv.Configuration.ShouldQuote = (field, context) => true;
        csv.Configuration.Delimiter = ";";

        foreach (var items in list)
        {
            foreach (var item in items)
            {
                csv.WriteField(item);
            }                    
            csv.NextRecord();

            writer.Flush();
            stream.Position = 0;

            yield return reader.ReadToEnd().TrimEnd('\n');

            stream.Position = 0;
        }   
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.