list和datatable的相互轉化
阿新 • • 發佈:2019-02-01
list轉datatble
public static DataTable ListToDataTable(IList list) { //返回物件result 例項化 DataTable result = new DataTable(); //list不為空 if (list.Count > 0) { //得到list的某條資料的屬性集合 PropertyInfo[] propertys = list[0].GetType().GetProperties(); //遍歷這些集合 foreach (PropertyInfo pi in propertys) { //獲取屬性的型別 pi.Name表示屬性名稱 Type colType = pi.PropertyType; //當型別為Nullable<>時 if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } //給datatable動態新增列 引數列名稱,型別 result.Columns.Add(pi.Name, colType); } //下面給datatable新增資料 for (int i = 0; i < list.Count; i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in propertys) { //得到屬性值,新增到tempList object obj = pi.GetValue(list[i], null); tempList.Add(obj); } object[] array = tempList.ToArray(); //LoadDataRow方法是查詢和更新特定行。如果找不到任何匹配行,則使用給定值建立新行 result.LoadDataRow(array, true); } } return result; }
datable轉list可參考我的這篇文章:http://blog.csdn.net/zhangxiaomin1992/article/details/50476029