对象实体到CSV序列化/转换

uhu*_*uhu 15 .net c#

如何在C#中将所有值(属性)写入csv格式化字符串?例如:

class Person(string firstName, string lastName, int_age);
Person person = new Person("Kevin","Kline",33);
Run Code Online (Sandbox Code Playgroud)

现在我想要一个字符串"Kevin; Kline; 33"

换句话说,我想将对象序列化为CSV

Stu*_*tLC 13

看看Josh Close的优秀CSVHelper

var person = new Person("Kevin","Kline",33);
using (var csv = new CsvWriter(new StreamWriter("file.csv")))
{
    csv.Configuration.HasHeaderRecord = false;
    csv.Configuration.Delimiter = ';';
    csv.WriteRecord(person);
}
Run Code Online (Sandbox Code Playgroud)

输出:

Kevin;Kline;33
Run Code Online (Sandbox Code Playgroud)

  • 最好的部分是它可用于.Net Core (4认同)

Oli*_*bes 9

通过使用反射,您可以从对象中检索属性信息

foreach (PropertyInfo prp in obj.GetType().GetProperties()) {
   if (prp.CanRead) {
      object value = prp.GetValue(obj, null);
      string s = value == null ? "" : value.ToString();
      string name = prp.Name;
      ...
   }
} 
Run Code Online (Sandbox Code Playgroud)

GetProperties方法有一个过载接受,BindingFlags通过它可以确定您需要哪种属性,如私有/公共实例/静态.

你可以像这样组合它们

var properties = type.GetProperties(BindingFlags.Public | 
                                    BindingFlags.NonPublic | 
                                    BindingFlags.Instance);
Run Code Online (Sandbox Code Playgroud)

适用于您的问题,您可以写

List<Person> people = ...;
Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
var sb = new StringBuilder();

// First line contains field names
foreach (PropertyInfo prp in properties) {
   if (prp.CanRead) {
      sb.Append(prp.Name).Append(';');
   }
}
sb.Length--; // Remove last ";"
sb.AppendLine();

foreach (Person person in people) {
    foreach (PropertyInfo prp in properties) {
       if (prp.CanRead) {
          sb.Append(prp.GetValue(person, null)).Append(';');
       }
    }
    sb.Length--; // Remove last ";"
    sb.AppendLine();
}

File.AppendAllText("C:\Data\Persons.csv", sb.ToString());
Run Code Online (Sandbox Code Playgroud)

将字符串括在双引号中并通过将它们加倍来转义它们包含的双引号也是一个好主意.


M. *_*. X 2

你可以使用这样的东西:

...
        PropertyInfo[] properties = obj.GetType().GetProperties();
        string CSVRow = "";
        foreach (PropertyInfo pi in properties)
        {
            CSVRow = CSVRow + pi.GetValue(obj, null) + ";";
        }
        CSVRow.Remove(CSVRow.Length - 1, 1);
...
Run Code Online (Sandbox Code Playgroud)

  • ...但还需要实施引用/转义规则。 (3认同)