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.
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"