2009/5/30 18:12| 閱讀數 : 1897 | 我要推薦 | Add Comment | 文章分類: ADO.Net | 訂閱
1. How to convert an IEnumerable to a DataTable in the same way as we use ToList or ToArray
* DataSet does not support System.Nullable<>.
DataSet does not support System.Nullable<>.
2. LINQ to DataTable
3. 有時候 List<T> 沒有資料會發生 Exception 改寫如下
/// <summary> /// 將 IEnumerable 轉為 DataTable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection">The collection.</param> /// <returns></returns> public static DataTable ToDataTable<T>(this IEnumerable<T> collection) { var dtReturn = new DataTable(); // column names var oProps = typeof(T).GetProperties(); foreach (var pi in oProps) { var colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); } // Could add a check to verify that there is an element 0 foreach (var rec in collection) { var dr = dtReturn.NewRow(); foreach (var pi in oProps) { dr[pi.Name] = pi.GetValue(rec, null) ?? DBNull.Value; } dtReturn.Rows.Add(dr); } return (dtReturn); }