正在尋找,並就如何動態列表轉換爲databale, C#,請指教開裂我的大腦,感謝轉換的動態列表,數據表C#
List<dynamic>dlist=new List<dynamic>
到
DataTable
正在尋找,並就如何動態列表轉換爲databale, C#,請指教開裂我的大腦,感謝轉換的動態列表,數據表C#
List<dynamic>dlist=new List<dynamic>
到
DataTable
以下是可以將任何列表對象轉換爲數據表的方法..
public DataTable ConvertToDataTable<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;
}
不適用於列表
使用此功能,
public static DataTable ConvertToDatatable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for(int i = 0 ; i < props.Count ; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
不適用於列表
我不知道爲什麼你需要這個,但是,你可以使用這個ObjectShredder
使用反射,可以任何轉換爲DataTable
,所以即使是動態或匿名類型:
Implement CopyToDataTable<T>
Where the generic Type T
Is Not a DataRow
public DataTable ToDataTable<T>(dynamic items)
{
DataTable dtDataTable = new DataTable();
if (items.Count == 0) return dtDataTable;
((IEnumerable)items[0]).Cast<dynamic>().Select(p => p.Name).ToList().ForEach(col => { dtDataTable.Columns.Add(col); });
((IEnumerable)items).Cast<dynamic>().ToList().
ForEach(data =>
{
DataRow dr = dtDataTable.NewRow();
((IEnumerable)data).Cast<dynamic>().ToList().ForEach(Col => { dr[Col.Name] = Col.Value; });
dtDataTable.Rows.Add(dr);
});
return dtDataTable;
}
這工作對我來說,雖然我不得不交換「名稱」的「鑰匙」,因爲我的枚舉包含KeyValuePair –
你的意思是,項目中的每個屬性/字段都應該成爲數據表中的列?如果'dlist'中的每個項目都是不同類型的呢?最重要的是:你已經嘗試過了什麼?顯示你的努力。 – MarcinJuraszek