将嵌套列表值写入CSV文件 [英] Writing nested list values to CSV file

查看:273
本文介绍了将嵌套列表值写入CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有嵌套列表属性的类,我试图将值写入CSV文件,但是我得到的输出附有[{}],如下所示:

I have class with nested list properties, I am trying to write the value to CSV file, but I am getting output appended with [{ }] like shown below:

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文件输出如下所示:

I want my output in CSV file like shown below:

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文件

I am using ServiceStack.Text to create CSV file from object

ServiceStack.Text.CsvSerializer.SerializeToWriter<TRoot>(TRoot, writer);

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

推荐答案

为单条csv行定义新类:

Define a new class for single csv line:

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 <$ c转换为行集合$ c> SelectMany 方法:

Now you can transfrom your objects into collection of lines with Linq SelectMany method:

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

这篇关于将嵌套列表值写入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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