IList--->DataTable
using System.Collections;
using System.Reflection;
using System.Data;
using System;
public class CADataConverter
{
private static Hashtable types = new Hashtable();
private CADataConverter()
{ }
public static DataTable ToDataTable(IList list)
{
if (list == null)
{
throw new ArgumentNullException("List","List can't be null");
}
if (list.Count < 1)
{
throw new ArgumentOutOfRangeException("List", "List can't be empty");
}
object obj = list[0];
if (obj == null)
{
throw new ArgumentOutOfRangeException("List","First imem can't be null");
}
//
return ToDataTable(list, obj.GetType());

}
public static DataTable ToDataTable(IList list,Type t)
{
DataTable dt = (DataTable)types[t];
if (dt == null)
{
CreateShell(t);
}
else
{
dt = dt.Clone();
}
if (list == null || list.Count < 1)
{ return dt; }
foreach (object item in list)
{
if (item == null)
{
DataRow dr = dt.NewRow();
/*dr[0]=
dr[1]=*/
foreach (DataColumn col in dt.Columns)
{
dr[col.ColumnName]=t.GetProperty(col.ColumnName).GetValue(item,null);
}
dt.Rows.Add(dr);
}
}
return dt;

}
protected static DataTable CreateShell(Type t)
{
DataTable dt = new DataTable(t.Name);
PropertyInfo[] infos = t.GetProperties();
foreach (PropertyInfo info in infos)
{
if(info.CanRead)
{
string str = info.PropertyType.ToString();
switch (str)
{
case "System.String":
case "System.Int32":
case "System.Boolean":
case "System.Double":
case "System.Guid":
dt.Columns.Add(info.Name, info.PropertyType);
break;
}
}
}
types[t] = dt;
return dt;
}
}



浙公网安备 33010602011771号