将泛型类转换成DataTable

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;


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值