积极答复者
关于使用List<T>生成DataTable并填充

问题
-
public DataTable listToDataTable<T>(List <T> list)
{
DataTable dt = new DataTable();
for (int i = 0; i < list[0].GetType().GetProperties().Count(); i++)
{
dt.Columns .Add (list [0].GetType ().GetProperties ()[i].Name ,list[0].GetType ().GetProperties ()[i].GetType () ); //这句有问题,老得不到属性的类型
}
for (int j = 0; j < list.Count; j++)
{
dt.Rows.Add();
for (int i = 0; i < list[0].GetType().GetProperties().Count(); i++)
{
object val=list[j].GetType().GetProperties()[i].GetValue(list[j], null);
dt.Rows[j][list[0].GetType().GetProperties()[i].Name] = val;
}
}
return dt;
}
答案
全部回复
-
是的,问题就在于int?。这个问题解决思路是这样的:找到Nullable类型的字段,然后转换成对应的值类型。
这样第一个for循环的代码可以修改为:
for (int i = 0; i < list[0].GetType().GetProperties().Count(); i++) { var property = list[0].GetType().GetProperties()[i]; Type columnType = property.PropertyType; if (property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) columnType = property.PropertyType.GetGenericArguments()[0]; dt.Columns.Add(property.Name, columnType); }
这样就可以避免Nullable类型了。