uncategorized

IEnumerable轉成DataTable

IEnumerable<T>這個型別在Framework3.5之後開始常用,且Linq語法對於某些程式撰寫與處理變成方便許多,甚至在處理像是Linq to SQL等模式也很方便,但是不可諱言的,在企業中很多系統往往還是需透過Datatable或是Dataset物件進行物件傳遞,尤其在用完IEnumerable(ex:var)之後要在系統進行資料傳遞或是後續處理時,要用for或是
foreach組成Datatable是一件很麻煩的事情,且在企業這種想要讓大家快速開發思維下,這是很浪費時間,因此,想說有沒有一個可以快速的做法,讓我們可以快速進行資料轉換。於是,參考到網路一種做法

將此方法可以寫成一個component或是method,下次用到就簡單多了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public static 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;
}

使用方法

1
2
3
4
var a =from s in dd
select new {s.name,s.tel};
Datatable dt=LinqQueryToDataTable(a);