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

我正在使用 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;

}


慕神8447489
浏览 126回答 2
2回答

猛跑小猪

通用转换:public DataTable ListToDataTable<T>(IList<T> data)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; PropertyDescriptorCollection properties =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TypeDescriptor.GetProperties(typeof(T));&nbsp; &nbsp; &nbsp; &nbsp; DataTable table = new DataTable();&nbsp; &nbsp; &nbsp; &nbsp; foreach (PropertyDescriptor prop in properties)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);&nbsp; &nbsp; &nbsp; &nbsp; foreach (T item in data)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DataRow row = table.NewRow();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (PropertyDescriptor prop in properties)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table.Rows.Add(row);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return table;&nbsp; &nbsp; }

qq_笑_17

你的问题是你在它的开头添加。您所要做的是实例化它,然后分配值,最后将其添加到数据表中。 此外,将添加信息更改为下一行DataRowdr[f.Name] = f.GetValue(o, null);代码如下:public static DataTable ObjectToData(object o){&nbsp; &nbsp; DataTable dt = new DataTable("OutputData");&nbsp; &nbsp; DataRow dr = dt.NewRow();&nbsp; &nbsp; o.GetType().GetProperties().ToList().ForEach(f =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f.GetValue(o, null);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dt.Columns.Add(f.Name, typeof(string));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dr[f.Name] = f.GetValue(o, null);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (Exception e)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(e.Message);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; dt.Rows.Add(dr);&nbsp; &nbsp; return dt;}您可以在此处找到一个示例&nbsp;https://dotnetfiddle.net/EeegHg
打开App,查看更多内容
随时随地看视频慕课网APP