第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

把對象(字符串列表)轉(zhuǎn)換為數(shù)據(jù)表

把對象(字符串列表)轉(zhuǎn)換為數(shù)據(jù)表

PHP
慕神8447489 2024-01-20 22:21:05
我正在使用 C# 和 .net core。我有一個(gè)由多個(gè)字符串列表組成的對象,我想將這個(gè)對象轉(zhuǎn)換為數(shù)據(jù)表。我嘗試過此代碼,但失敗了: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貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊

通用轉(zhuǎn)換:


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;

    }


查看完整回答
反對 回復(fù) 2024-01-20
?
qq_笑_17

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超7個(gè)贊

你的問題是你在它的開頭添加。您所要做的是實(shí)例化它,然后分配值,最后將其添加到數(shù)據(jù)表中。 此外,將添加信息更改為下一行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;

}

您可以在此處找到一個(gè)示例 https://dotnetfiddle.net/EeegHg


查看完整回答
反對 回復(fù) 2024-01-20
  • 2 回答
  • 0 關(guān)注
  • 212 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)