public static DataTable ToDataTable<T>(List<T> entitys)
2 {
3
4 //检查实体集合不能为空
5 if (entitys ==null|| entitys.Count<1)
6 {
7 throw new Exception("需转换的集合为空");
8 }
9
10 //取出第一个实体的所有Propertie
11 Type entityType= entitys[0].GetType();
12 PropertyInfo[] entityProperties= entityType.GetProperties();
13
14 //生成DataTable的structure
15 //生产代码中,应将生成的DataTable结构Cache起来,此处略
16 DataTable dt = new DataTable();
17 for (int i = 0; i < entityProperties.Length; i++)
18 {
19 dt.Columns.Add(entityProperties[i].Name,entityProperties[i].PropertyType);
20 }
21
22 //将所有entity添加到DataTable中
23 foreach (object entity in entitys)
24 {
25 //检查所有的的实体都为同一类型
26 if (entity.GetType()!=entityType)
27 {
28 throw new Exception("要转换的集合元素类型不一致");
29 }
30 object[] entityValues = new object[entityProperties.Length];
31 for (int i = 0; i < entityProperties.Length; i++)
32 {
33 entityValues[i] = entityProperties[i].GetValue(entity, null);
34
35 }
36 dt.Rows.Add(entityValues);
37 }
38 return dt;
39 }
将泛型类转换成DataTable
public static DataTable Fill<T>(IList<T> objlist)
{
if (objlist == null || objlist.Count <= 0)
{
return null;
}
DataTable dt = new DataTable(typeof(T).Name);
DataColumn column;
DataRow row;
System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (T t in objlist)
{
if (t == null)
{
continue;
}
row = dt.NewRow();
for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
{
System.Reflection.PropertyInfo pi = myPropertyInfo[i];
string name = pi.Name;
if (dt.Columns[name] == null)
{
column = new DataColumn(name, pi.PropertyType);
dt.Columns.Add(column);
}
row[name] = pi.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}
使用泛型类List,不用ArrayList,比下面Fill方法的性能提高
DataSet转泛型
public static IList<T> FillModel(DataSet ds)
{
List<T> l = new List<T>();
T model = default(T);
foreach (DataRow dr in ds.Tables[0].Rows)
{
model = Activator.CreateInstance<T>();
foreach (DataColumn dc in dr.Table.Columns)
{
PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName);
if (dr[dc.ColumnName] != DBNull.Value)
pi.SetValue(model, dr[dc.ColumnName], null);
else
pi.SetValue(model, null, null);
}
l.Add(model);
}
return l;
}