c# – 有一个快速的方式将一个实体转换为.csv文件?

前端之家收集整理的这篇文章主要介绍了c# – 有一个快速的方式将一个实体转换为.csv文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
目前我有:
string outputRow = string.Empty;
        foreach (var entityObject in entityObjects)
        {
            outputRow = entityObject.field1 + "," + entityObject.Field2  etc....
        }

我还是新的实体框架,有更快的方法吗?

解决方法

示例代码显示了一种简单而强大的方式来完成所需的操作,而无需使用反编译代码来强制编写属性名称
/// <summary>
 /// Creates a comma delimeted string of all the objects property values names.
 /// </summary>
 /// <param name="obj">object.</param>
 /// <returns>string.</returns>
 public static string ObjectToCsvData(object obj)
 {
     if (obj == null)
     {
         throw new ArgumentNullException("obj","Value can not be null or Nothing!");
     }

     StringBuilder sb = new StringBuilder();
     Type t = obj.GetType();
     PropertyInfo[] pi = t.GetProperties();

     for (int index = 0; index < pi.Length; index++)
     {
         sb.Append(pi[index].GetValue(obj,null));

         if (index < pi.Length - 1)
         {
            sb.Append(",");
         }
     }

     return sb.ToString();
 }

更多关于这个

Objects to CSV

How can i convert a list of objects to csv

Are there any CSV readers/writer lib’s in c#

Writing a CSV file in .net

LINQ to CSV : Getting data the way you want

LINQ to CSV library

原文链接:https://www.f2er.com/csharp/95517.html

猜你在找的C#相关文章