转自:http://www.cnblogs.com/zoofooo/archive/2012/08/02/2619669.html
1 using System; 2 using System.Data; 3 using System.Collections; 4 using System.Collections.Generic; 5 using System.Configuration; 6 using System.Reflection; 7 using System.Linq; 8 using System.Xml.Linq; 9 10 namespace UserFunction 11 { 12 /// <summary> 13 /// Summary description for LinqToDataTable 14 /// </summary> 15 static public class LinqToDataTable 16 { 17 static public DataTable ToDataTable<T>(this IEnumerable<T> varlist, CreateRowDelegate<T> fn) 18 { 19 20 DataTable dtReturn = new DataTable(); 21 22 // column names 23 24 PropertyInfo[] oProps = null; 25 26 // Could add a check to verify that there is an element 0 27 28 foreach (T rec in varlist) 29 { 30 31 // Use reflection to get property names, to create table, Only first time, others will follow 32 33 if (oProps == null) 34 { 35 36 oProps = ((Type)rec.GetType()).GetProperties(); 37 38 foreach (PropertyInfo pi in oProps) 39 { 40 // 当字段类型是Nullable<>时 41 Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) 42 { 43 44 colType = colType.GetGenericArguments()[0]; 45 46 } 47 48 dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); 49 50 } 51 52 } 53 54 DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps) 55 { 56 57 dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null); 58 59 } 60 61 dtReturn.Rows.Add(dr); 62 63 } 64 65 return (dtReturn); 66 67 } 68 69 public delegate object[] CreateRowDelegate<T>(T t); 70 } 71 } 72 73 /* 74 * 示例: 75 * var query = from ....; 76 * DataTable dt = query.ToDataTable(rec => new object[] { query }); 77 * 78 */