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

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
- 2 回答
- 0 關注
- 226 瀏覽
添加回答
舉報