C# 如何从 List<String[]> 创建一个 csv 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13815634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a csv file from List<String[]>
提问by Gnanasekaran Kuppusamy
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 中有一个如下所示的多维值
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.
任何帮助将非常感激。
采纳答案by Marc Gravell
At the simplest level, not handling quoting / escaping / multi-line CSV issues, then just loop; maybe something like:
在最简单的层面上,不处理引用/转义/多行 CSV 问题,然后循环;也许是这样的:
using (var file = File.CreateText(path))
{
foreach(var arr in lst)
{
file.WriteLine(string.Join(",", arr));
}
}
or a tinybit 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();
}
}
回答by Jan Van Herck
use linq:
使用 linq:
File.WriteAllLines("text.txt", lst.Select(x => string.Join(",", x)));

