public static DataTable GetDataTable<T>( IEnumerable<T> list,string tableName) { DataTable dtResult = new DataTable(); dtResult.TableName = tableName; List<PropertyInfo> propertiyInfos = new List<PropertyInfo>(); //生成各列 Array.ForEach<PropertyInfo>(typeof(T).GetProperties(), p => { propertiyInfos.Add(p); dtResult.Columns.Add(p.Name, p.PropertyType); }); //生成各行 foreach (var item in list) { if (item == null) { continue; } DataRow dataRow = dtResult.NewRow(); propertiyInfos.ForEach(p => dataRow[p.Name] = p.GetValue(item, null)); dtResult.Rows.Add(dataRow); } return dtResult; }
时间: 2024-10-06 14:52:29