public DataTable LinqQueryToDataTable<T>(IEnumerable<T> query) { DataTable tbl = new DataTable(); PropertyInfo[] props = null; foreach (T item in query) { if (props == null) //尚未初始化 { Type t = item.GetType(); props = t.GetProperties(); foreach (PropertyInfo pi in props) { Type colType = pi.PropertyType; //針對Nullable<>特別處理 if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>)) colType = colType.GetGenericArguments()[0]; //建立欄位 tbl.Columns.Add(pi.Name, colType); } } DataRow row = tbl.NewRow(); foreach (PropertyInfo pi in props) row[pi.Name] = pi.GetValue(item, null) ?? DBNull.Value; tbl.Rows.Add(row); } return tbl; }
或是使用 Json 的方式來轉換,不過這方式最好使用在資料量比較小的情境下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public DataTable LinqToDataTableByJson<T>(IEnumerable<T> query) { JArray jObjects = new JArray(); PropertyInfo[] props = null; foreach (var item in query) { Type t = item.GetType(); props = t.GetProperties(); var jo = new JObject(); foreach (PropertyInfo pi in props) jo.Add(pi.Name, (JToken)pi.GetValue(item, null).ToString()); jObjects.Add(jo); } return JsonConvert.DeserializeObject<DataTable>(jObjects.ToString()); }