将嵌套列表值写入CSV文件

时间:2018-01-17 10:18:49

标签: c# asp.net csv

我有使用嵌套列表属性的类,我正在尝试将值写入CSV文件,但我得到的输出附加了[{}],如下所示:

Client  TDeals
ABC     [{DealName:59045599,TShape:[{StartDate:"2014-01-
        28T23:00:00",EndDate:"2014-01-28T23:30:00",Volume:0.00},
        {StartDateTime:"2014-01-                
        28T23:30:00",EndDateTime:"2014-01-29T00:00:00",Volume:0.00}}]

我希望我的输出在CSV文件中,如下所示:

Client      DealNo        StartDate        EndDate         Volume
ABC        59045599         -                -               -

类属性

  public class TRoot
    {
            public string Client { get; set; }
            public List<TDeal> Deals { get; set; }
    }

  public class TDeal
  {
    public string DealName{get;set;}
    public List<TInterval> TShape { get; set; }
  }

  public class TInterval
  {
     public string StartDate{ get; set; }
     public string EndDate{ get; set; }
     public string Volume {get;set;}
  }

我正在使用ServiceStack.Text从对象

创建CSV文件
ServiceStack.Text.CsvSerializer.SerializeToWriter<TRoot>(TRoot, writer);

参考网址 https://github.com/ServiceStack/ServiceStack.Text

3 个答案:

答案 0 :(得分:3)

为单个csv行定义一个新类:

public class CsvLine
{
    public string Client { get; set; }
    public string DealName { get; set; }
    public string StartDate { get; set; }
    public string EndDate { get; set; }
    public string Volume { get; set; }
}

现在,您可以使用Linq SelectMany方法将对象转换为行集合:

TRoot root = ...
var lines = root.Deals.SelectMany(d => d.TShape.Select(s => new CsvLine
{
    Client = root.Client,
    DealName = d.DealName,
    StartDate = s.StartDate,
    EndDate = s.EndDate,
    Volume = s.Volume
})).ToArray();

然后在该集合上调用SerializeToWriter

答案 1 :(得分:2)

我会建议&#34;展平&#34;您的输出为CSV。

再创建一个类,它将成为您希望在CSV文件中拥有的内容的镜像。在写入文件之前,请将TRoot转换为该新类并将其写入CSV。

快速而优雅的解决方案:)

答案 2 :(得分:0)

您可以尝试Cinchoo ETL来创建CSV文件。首先,您必须使用Linq展平根对象并将它们传递给CSV编写器以创建文件。

下面的示例显示如何

private static void Test()
{
    TRoot root = new TRoot() { Client = "ABC", Deals = new List<TDeal>() };
    root.Deals.Add(new TDeal
    {
        DealName = "59045599",
        TShape = new List<TInterval>()
    {
        new TInterval { StartDate = DateTime.Today.ToString(), EndDate = DateTime.Today.AddDays(2).ToString(), Volume = "100" },
        new TInterval { StartDate = DateTime.Today.ToString(), EndDate = DateTime.Today.AddDays(2).ToString(), Volume = "200" }
    }
    });

    using (var w = new ChoCSVWriter("nestedObjects.csv").WithFirstLineHeader())
    {
        w.Write(root.Deals.SelectMany(d => d.TShape.Select(s => new { ClientName = root.Client, DealNo = d.DealName, StartDate = s.StartDate, EndDate = s.EndDate, Volume = s.Volume })));
    }

}

输出结果为:

ClientName,DealNo,StartDate,EndDate,Volume
ABC,59045599,1/17/2018 12:00:00 AM,1/19/2018 12:00:00 AM,100
ABC,59045599,1/17/2018 12:00:00 AM,1/19/2018 12:00:00 AM,200

有关它的更多信息,请访问

中的codeproject文章

https://www.codeproject.com/Articles/1155891/Cinchoo-ETL-CSVWriter

免责声明:我是这个图书馆的作者。