[英]How to create a csv file from List<String[]>
Can anyone help me to create a csv file from List, my scenario is, i have a multi dimensional values like below in a List 任何人都可以帮我从List创建一个csv文件,我的场景是,我在列表中有如下面的多维值
List<string[]> lst = new List<string[]>();
lst= csv1.ToList();
lst contains the values like, lst包含像,
lst[0] = {string[53]}
lst[1] = {string[53]}
lst[2] = {string[53]}
lst[3] = {string[53]}
lst[4] = {string[53]}
and string[53] contains the values like 和string [53]包含的值如
lst[0]
string[0] = "abc"
string[1] = "def"
string[2] = "ghi"
string[3] = "jkl"
string[4] = "mno"
...
lst[1]
string[0] = "123"
string[1] = "456"
string[2] = "789"
string[3] = "10"
string[4] = "11"
...
I just wanted to write this multi-dimensional list to csv file as each item in lst[] to rows in csv and each item in string[] to columns such that the final output in my csv is 我只想将这个多维列表写入csv文件作为lst []中的每个项目到csv中的行和string []中的每个项目到列,这样我的csv中的最终输出是
abc,def,ghi,jkl,mno
123,456,789,10,11
Any help would be really appreciated. 任何帮助将非常感激。
使用linq:
File.WriteAllLines("text.txt", lst.Select(x => string.Join(",", x)));
At the simplest level, not handling quoting / escaping / multi-line CSV issues, then just loop; 在最简单的层面上,不处理引用/转义/多行CSV问题,然后循环; maybe something like:
也许是这样的:
using (var file = File.CreateText(path))
{
foreach(var arr in lst)
{
file.WriteLine(string.Join(",", arr));
}
}
or a tiny bit more efficient (no intermediary string): 或一点点更有效(无中介字符串):
using (var file = File.CreateText(path))
{
foreach (var arr in lst)
{
if (String.IsNullOrEmpty(arr)) continue;
file.Write(arr[0]);
for(int i = 1 ; i < arr.Length ; i++)
{
file.Write(',');
file.Write(arr[i]);
}
file.WriteLine();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.