gpt4 book ai didi

c# - 有没有一种快速的方法可以将实体转换为 .csv 文件?

转载 作者:太空狗 更新时间:2023-10-29 17:29:54 27 4
gpt4 key购买 nike

目前,我有:

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

我还是 Entity Framework 的新手,有没有更快的方法?

最佳答案

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

 /// <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

关于c# - 有没有一种快速的方法可以将实体转换为 .csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3199604/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com