C#-如何编写List< List< string>>到CSV文件? [英] C# - How to write a List<List<string>> to CSV file?

查看:213
本文介绍了C#-如何编写List< List< string>>到CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C#将一些数据写入CSV文件.

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

此刻是我的代码:

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.

然后,我用'\ t'分隔符分隔每一行,并将该行的每一部分添加到列表中.

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.

所以列表看起来像:

  • List1 {txt1,txt 2} =第一行
  • 列表2 {txt3,txt 4,txt 5,txt 6} =第二行
  • List3 {txt7,txt 8,txt 9,txt 10} =第三行
  • List4 {txt 11,txt 12}等

所有列表的长度都不尽相同.

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

我要做的是将所有列表写入CSV文件.

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

每个列表将填充一行并有一定数量的列,具体取决于列表的长度(即txt1应该是(row1,col1),txt2应该是(row1,col2),txt3应该是(row2,col1 ),则txt4为(row2,col2)...).

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

我该怎么做?

谢谢

推荐答案

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));
    });
}

这篇关于C#-如何编写List&lt; List&lt; string&gt;&gt;到CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆