将List集合类转换成DataTable

来源:互联网 发布:算法基础 第5版 编辑:程序博客网 时间:2024/05/21 19:48
public DataTable GetList(SMSys_Document Document)
{
DataTable dt = new DataTable();
//df.SMSys_YearTask.Where(c => c.Creater == yt.Creater && c.Editor == yt.Creater).ToList();
var df = new SMSysDBContext();
List<SMSys_Document> list = df.SMSys_Document.ToList();
dt=ListToDataTable(list);
return dt;
}
///  
/// 将List集合类转换成DataTable 
///  
/// 集合 
///  
public static DataTable ListToDataTable(IList list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
//获取类型
Type colType = pi.PropertyType;
//当类型为Nullable<>时
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
result.Columns.Add(pi.Name, colType);
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
0 0
原创粉丝点击