为了账号安全,请及时绑定邮箱和手机立即绑定

把对象(字符串列表)转换为数据表

把对象(字符串列表)转换为数据表

PHP
慕神8447489 2024-01-20 22:21:05
我正在使用 C# 和 .net core。我有一个由多个字符串列表组成的对象,我想将这个对象转换为数据表。我尝试过此代码,但失败了:public static DataTable ObjectToData(object o){    DataTable dt = new DataTable("OutputData");    DataRow dr = dt.NewRow();    dt.Rows.Add(dr);    o.GetType().GetProperties().ToList().ForEach(f =>    {        try        {            f.GetValue(o, null);            dt.Columns.Add(f.Name, typeof(string));            dt.Rows[0][f.Name] = f.GetValue(o, null);        }        catch { }    });    return dt;}
查看完整描述

2 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

通用转换:


public DataTable ListToDataTable<T>(IList<T> data)

    {

        PropertyDescriptorCollection properties =

            TypeDescriptor.GetProperties(typeof(T));


        DataTable table = new DataTable();


        foreach (PropertyDescriptor prop in properties)

                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);


        foreach (T item in data)

        {

            DataRow row = table.NewRow();

            foreach (PropertyDescriptor prop in properties)

            {

               row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;

            }

            table.Rows.Add(row);

        }

        return table;

    }


查看完整回答
反对 回复 2024-01-20
?
qq_笑_17

TA贡献1818条经验 获得超7个赞

你的问题是你在它的开头添加。您所要做的是实例化它,然后分配值,最后将其添加到数据表中。 此外,将添加信息更改为下一行DataRowdr[f.Name] = f.GetValue(o, null);


代码如下:


public static DataTable ObjectToData(object o)

{

    DataTable dt = new DataTable("OutputData");


    DataRow dr = dt.NewRow();



    o.GetType().GetProperties().ToList().ForEach(f =>

    {

        try

        {

            f.GetValue(o, null);

            dt.Columns.Add(f.Name, typeof(string));

            dr[f.Name] = f.GetValue(o, null);

        }

        catch (Exception e)

        {

            Console.WriteLine(e.Message);

        }

    });


    dt.Rows.Add(dr);


    return dt;

}

您可以在此处找到一个示例 https://dotnetfiddle.net/EeegHg


查看完整回答
反对 回复 2024-01-20
  • 2 回答
  • 0 关注
  • 38 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信