写CSV文件的对象C#列表 [英] Write C# Lists of objects in CSV file

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

问题描述

我已经有大小200.I的8阵元一个C#对象需要这些阵列打印到CSV在各自的标签文件。 。数据可能包含字符串,int和double

I have a C# object having 8 array elements of size 200.I need to print these arrays into a CSV file on respective labels. Data might contain string,int and double.

例如:


time   time1   time2  Day  time4  time4 time5 time6 time7
1       5       9     Mon   7.0    8      9    5     NA
2
3
3
.
.
200    200    200    Sun   200    200   200   200    200



哎呀,时间点等都是标签(标题)中的数据(有8名单200元),应该将这些标签下写的。 !
感谢您的答复。

Oops, time1 etc are labels(Header) the data(8 lists having 200 elements) should write under these labels. Appreciate your response !

推荐答案

您可以写一个通用的函数写的对象:

You could write a generic function to write the objects:

public void WriteCSV<T>(IEnumerable<T> items, string path)
{
  Type itemType = typeof(T);
  var props = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                      .OrderBy(p => p.Name);

  using (var writer = new StreamWriter(path))
  {
    writer.WriteLine(string.Join(", ", props.Select(p => p.Name)));

    foreach (var item in items)
    {
      writer.WriteLine(string.Join(", ", props.Select(p => p.GetValue(item, null))));
    }
  }
}

用于为:

var people = new List<Person> { new Person("Matt", "Abbott"), new Person("John Smith") };
WriteCSV(people, @"C:\people.csv");



其中的可能的输出:

Forename, Surname
Matt", Abbott"
John", Smith"

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

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