list转datatble
public static DataTable ListToDataTable(IList list)
{
//返回对象result 实例化
DataTable result = new DataTable();
//list不为空
if (list.Count > 0)
{
//得到list的某条数据的属性集合
PropertyInfo[] propertys = list[0].GetType().GetProperties();
//遍历这些集合
foreach (PropertyInfo pi in propertys)
{
//获取属性的类型 pi.Name表示属性名称
Type colType = pi.PropertyType;
//当类型为Nullable<>时
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
//给datatable动态添加列 参数列名称,类型
result.Columns.Add(pi.Name, colType);
}
//下面给datatable添加数据
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
//得到属性值,添加到tempList
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
//LoadDataRow方法是查找和更新特定行。如果找不到任何匹配行,则使用给定值创建新行
result.LoadDataRow(array, true);
}
}
return result;
}
datable转list可参考我的这篇文章:http://blog.youkuaiyun.com/zhangxiaomin1992/article/details/50476029