【问题标题】:Loop over Generic List of Lists and write in csv format (C#)循环遍历列表的通用列表并以 csv 格式写入(C#)
【发布时间】:2018-02-14 08:34:46
【问题描述】:

我想将要保存为 csv 的列表的结果保存到编码为 UTF 的变量路径中。

但是当我用 foreach 在我的列表上循环时:

    foreach (String item in finalausgabe)
            {
                Console.WriteLine(ausgabe.GetType());
            }

我在控制台中得到以下结果(仅前五行用于预览)

System.Collections.Generic.List1[System.String]
System.Collections.Generic.List1[System.String]
System.Collections.Generic.List1[System.String]
System.Collections.Generic.List1[System.String]
System.Collections.Generic.List1[System.String]

但我的列表实际上是这样的:

“状态”“用户ID”“用户名”“Vorname”“Nachname”“Zweiter Vorname”
“活跃” “1” “testm” “测试” “M” “” “M” “” “Kuhnkies” “活跃” “10” “lext” Sofia Daasch “” “F” “” “Lex” “活跃”“102”“瑞特”安娜·达巴格“”“M”“”“瑞特” “活跃” “103” “buchmeiera” Lea Dabbert “” “M” “” “Buchmeier” “活跃”“104”“fuchss”艾米莉亚达贝尔斯“”“M”“”

正如您所见,它已经准备好作为制表符分隔的 csv,只需将其逐行保存在编码为“utf-8”的 csv 文件中。

【问题讨论】:

  • 你觉得.GetType() 是怎么回事
  • 获取我的类型.. 知道了,但是 .GetValue() 不起作用..

标签: c# list csv generic-list


【解决方案1】:

显然你应该写类似

foreach (String item in finalausgabe)
            {
                Console.WriteLine(item);
            }

【讨论】:

【解决方案2】:

我建议使用CsvHelper,并将您的数据排序为单独的字符串,例如:

class MyRecord
{
    public string Status {get; set;}
    public string UserId {get; set;}
    public string UserName {get; set;}
}

然后使用 CsvHelper 如下:

List<MyRecord> records = yourFilledList;
var textWriter = new StreamWriter("your file path",isAppend, Encoding.UTF8);
var csv = new CsvWriter( textWriter );
csv.WriteRecords( records );

至于foreach,该项目将在每次迭代中自动为您提供,因此您应该直接使用它,它遵循

Console.WriteLine(element);

有关 CsvHelper 以及如何安装 nuget 的更多信息,请查看this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    相关资源
    最近更新 更多