泛型和DataTable的属性
泛型转DataTable
public DataTable ToDataTable<TResult>(this IEnumerable<TResult> value) where TResult : class { //创建属性的集合 List<PropertyInfo> pList = new List<PropertyInfo>(); Type type = typeof(TResult); DataTable dt = new DataTable(); Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); }); foreach (var item in value) { //创建一个DataRow实例 DataRow row = dt.NewRow(); pList.ForEach(p => row[p.Name] = p.GetValue(item, null)); dt.Rows.Add(row); } return dt; }
按着模型设置datatable
public DataTable ConvertToDataTable<T>(List<ColunmData> colunmDatas, List<T> data) { var dataTable = new DataTable(); foreach (var it in colunmDatas) { dataTable.Columns.Add(new DataColumn(it.colunmEnglish, Type.GetType(it.dataType))); } DataColumnCollection colunms = dataTable.Columns;//datatable的属性值 //修改列属性 foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(T)))// 获取泛型的属性值
{ if (colunms.Contains(pd.Name))//存在该字段就赋值 { dataTable.Columns[pd.Name].DataType = pd.PropertyType; } } foreach (T it in data) { DataRow Row = dataTable.NewRow(); foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(T))) { if (colunms.Contains(pd.Name))//存在该字段就赋值 { Row[pd.Name] = pd.GetValue(it); } } dataTable.Rows.Add(Row); } return dataTable; }
/// <summary> /// 获取某一列的所有值 /// </summary> /// <typeparam name="T">列数据类型</typeparam> /// <param name="dtSource">数据表</param> /// <param name="filedName">列名</param> /// <returns></returns> public static List<T> GetColumnValues<T>(DataTable dtSource,string filedName) { return (from r in dtSource.AsEnumerable() select r.Field<T>("ID")).ToList<T>(); }