从列表创建csv而不复制某些列

时间:2015-01-27 10:34:37

标签: c# csv

我有一个集合(List<ProfileDo>),它具有以下结构......

ProfileDo
- StartDateTime
- EndDateTime
- Volume

我正在尝试创建一个看起来像

的csv文件
"StartDateTime", "EndDateTime", "Volume"

我正在努力寻找一种方法来停止复制&#34; StartDateTime&#34;,&#34; EndDateTime&#34;被添加到每个配置文件的csv并只使用一次并使用其他人的卷。任何帮助赞赏。

2 个答案:

答案 0 :(得分:0)

这可能听起来有线但可行,

您可以像Dictionary一样创建Dictionary<string, List<int>>。并将StartDateTimeEndDateTime合并到StartDateTime_EndDateTime之类的字符串中。现在,当您添加Volumes时,您将使用StartDateTimeEndDateTime进行组合,并使用ContainsKey()进行比较。

如果密钥存在,我们将Volume添加到相关列表,否则我们会创建一个新条目并添加。

This示例可能会有所帮助。

答案 1 :(得分:0)

如果我理解正确你需要的是类似于2级控制中断我们曾经称之为编写cobol程序。确保列表按StartDateTime和EndDateTime排序。然后当你循环时,你需要存储当前的StartDateTime和EndDateTime,当它不相同时。像这样:

DateTime? currentStartDatetime = null;
DateTime? currentStartDatetime = null;
string line;  // can use string builder for performance..

foreach (var profile in profiles)
{
  line = string.Empty;

  if (currentStartDateTime != profile.StartDateTime)
  {
     currentStartDateTime = profile.StartDateTime;
     line += profile.StartDateTime + ",";
  }
  else
  {
     line += ",";
  }

  if (currentEndDateTime != profile.EndDateTime)
  {
     currentEndDateTime = profile.EndDateTime;
     line += profile.EndDateTime + ",";
  }
  else
  {
     line += ",";
  }

  line += profile.Volume;

  Csv.WriteLine(line);
}