有一个快速的方法,将实体转换为.csv文件? [英] Is there a quick way to convert an entity to .csv file?
本文介绍了有一个快速的方法,将实体转换为.csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,我有:
string outputRow = string.Empty;
foreach (var entityObject in entityObjects)
{
outputRow = entityObject.field1 + "," + entityObject.Field2 etc....
}
我还是新的Entity框架,有更快的方式吗?
I'm still new to the Entity Framework, is there a quicker way?
推荐答案
示例代码显示一个简单而强大的方式来完成你想要的,而不需要硬编码属性名称(使用反射):
Sample code that shows a simple yet powerful way of accomplishing what you want with no need to hard code property names (using reflection):
/// <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();
}
更多:
Are there any CSV readers/writer lib’s in c#
LINQ to CSV : Getting data the way you want
这篇关于有一个快速的方法,将实体转换为.csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文