有没有快速的方法将实体转换为.csv文件?

目前,我有:

string outputRow = string.Empty; foreach (var entityObject in entityObjects) { outputRow = entityObject.field1 + "," + entityObject.Field2 etc.... } 

我还是entity framework的新手,有更快的方法吗?

示例代码,显示了一种简单而强大的方法来完成您想要的内容而无需硬编码属性名称(使用reflection):

  ///  /// Creates a comma delimeted string of all the objects property values names. ///  /// object. /// string. 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(); } 

更多关于此:

对象为CSV

如何将对象列表转换为csv

c#中是否有任何CSV读/写库?

在.net中写入CSV文件

LINQ to CSV:以您希望的方式获取数据

LINQ到CSV库

我采用了Leniel的建议并将其包装在一个function齐全的“编写器”中,该编写器还允许您过滤您想要编写的属性。 这是您的使用代码:

 public class CsvFileWriter { public static void WriteToFile(string filePath, List objs, string[] propertyNames) { var builder = new StringBuilder(); var propertyInfos = RelevantPropertyInfos(propertyNames); foreach (var obj in objs) builder.AppendLine(CsvDataFor(obj, propertyInfos)); File.WriteAllText(filePath, builder.ToString()); } public static void WriteToFileSingleFieldOneLine(string filePath, List objs, string propertyName) { var builder = new StringBuilder(); var propertyInfos = RelevantPropertyInfos(new[] { propertyName }); for (var i = 0; i < objs.Count; i++) { builder.Append(CsvDataFor(objs[i], propertyInfos)); if (i < objs.Count - 1) builder.Append(","); } File.WriteAllText(filePath, builder.ToString()); } private static List RelevantPropertyInfos(IEnumerable propertyNames) { var propertyInfos = typeof(T).GetProperties().Where(p => propertyNames.Contains(p.Name)).ToDictionary(pi => pi.Name, pi => pi); return (from propertyName in propertyNames where propertyInfos.ContainsKey(propertyName) select propertyInfos[propertyName]).ToList(); } private static string CsvDataFor(object obj, IList propertyInfos) { if (obj == null) return ""; var builder = new StringBuilder(); for (var i = 0; i < propertyInfos.Count; i++) { builder.Append(propertyInfos[i].GetValue(obj, null)); if (i < propertyInfos.Count - 1) builder.Append(","); } return builder.ToString(); } } 
 string csv = ""; //get property names from the first object using reflection IEnumerable props = entityObjects.First().GetType().GetProperties(); //header csv += String.Join(", ",props.Select(prop => prop.Name)) + "\r\n"; //rows foreach(var entityObject in entityObjects) { csv += String.Join(", ", props.Select( prop => ( prop.GetValue(entityObject, null) ?? "" ).ToString() ) ) + "\r\n"; } 
  • 最好将StringBuilder用于许多实体
  • 代码不检查entityObjects何时为空