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;
}

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
- 2 回答
- 0 關(guān)注
- 212 瀏覽
添加回答
舉報(bào)