代码改变世界

IList转换为DataTable

2011-03-05 10:59  杨延成  阅读(451)  评论(1编辑  收藏  举报
#region Conver IList to DataTable
///
/// IList泛型集合转换为DataTable
///
///
///
///
public DataTable ConverToDataTable(IList list)
{
if (list == null || list.Count < 1)
{
return null;
}
DataTable dt = new DataTable(typeof(T).Name);
///利用反射,获得泛型集合装载对象的公有属性或者实例属性名
System.Reflection.PropertyInfo[] myProperty = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);


///遍历属性集合
foreach (System.Reflection.PropertyInfo item in myProperty)
{
///以列的形式添加到DataTable
dt.Columns.Add(item.Name, item.PropertyType);
}
DataRow row;
///遍历集合内对象
foreach (T t in list)
{
row = dt.NewRow();
///将每个对象的属性值取出绑定列
foreach (System.Reflection.PropertyInfo item in myProperty)
{
row = item.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}
#endregion