List<T>/IEnumerable转换到DataTable/DataView

//这里是List<T> 转DataTable的方法主体

1
public DataTable ToDataTable<T>(List<T> items) 2 { 3 var tb = new DataTable(typeof(T).Name); 4 5 PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 6 7 foreach (PropertyInfo prop in props) 8 { 9 Type t = GetCoreType(prop.PropertyType); 10 tb.Columns.Add(prop.Name, t); 11 } 12 13 foreach (T item in items) 14 { 15 var values = new object[props.Length]; 16 17 for (int i = 0; i < props.Length; i++) 18 { 19 values[i] = props[i].GetValue(item, null); 20 } 21 22 tb.Rows.Add(values); 23 } 24 25 return tb; 26 }

下面是方法的使用:比如你有一个List<T>集合。
我这里是通过接口获得的List<T>,来演示。使用方法:

 1 new ListToDataTable().ToDataTable() 

ToDataTable()括号内就是你的List<t>。

 1 DataTable dtnn = new ListToDataTable().ToDataTable(await mService.GetProductlevel(Catalog_No)); 

posted @ 2022-03-11 11:20  醉意拥桃枝丶  阅读(168)  评论(0)    收藏  举报