亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

把對象(字符串列表)轉換為數據表

把對象(字符串列表)轉換為數據表

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 關注
  • 226 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號