我卡在了以下问题上:
我通常使用下面的函数将自定义数据传输到DataTable,但在这种情况下,输入数据是由列表组成的类。我只需要在每行中写入每个列表的第一个元素。你能帮我调整这个函数以实现这个目标吗?
基于Carra的回答,我尝试了下面的代码,但它没有识别出pType类型(类型或命名空间名称“pType”无法找到(是否缺少using指令或程序集引用?))
我通常使用下面的函数将自定义数据传输到DataTable,但在这种情况下,输入数据是由列表组成的类。我只需要在每行中写入每个列表的第一个元素。你能帮我调整这个函数以实现这个目标吗?
public List<int> xID { get; set; }
public List<string> xName { get; set; }
public List<string> xType { get; set; }
public List<string> xSource { get; set; }
public List<int> xmdID { get; set; }
public List<string> xMDName { get; set; }
public List<string> xUser { get; set; }
public static DataTable ListToDataTable<T>(IEnumerable<T> list)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (T entity in list)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
基于Carra的回答,我尝试了下面的代码,但它没有识别出pType类型(类型或命名空间名称“pType”无法找到(是否缺少using指令或程序集引用?))
var v = properties[i].GetValue(entity);
Type pType = properties[i].PropertyType;
if (pType.IsGenericType && pType.GetGenericTypeDefinition() == typeof(Nullable<>))
pType = Nullable.GetUnderlyingType(pType);
if (pType.IsEnum)
pType = Enum.GetUnderlyingType(pType);
if (v.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
values[i] = (v as List<pType>).First();
}
更新
我想这不是最好的解决方案,因为它不接受任何列表类型,但这是我能做到的最好的:
public static DataTable ListToDataTable<T>(IEnumerable<T> list)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
Type propertyType = info.PropertyType;
if (propertyType.IsGenericType | propertyType.GetGenericTypeDefinition() == typeof(Nullable<>) | propertyType.IsEnum)
propertyType = propertyType.GetGenericArguments()[0];
dataTable.Columns.Add(new DataColumn(info.Name, propertyType));
}
foreach (T entity in list)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
var v = properties[i].GetValue(entity);
Type pType = v.GetType().GetGenericArguments().FirstOrDefault();
if (v.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
if(pType == typeof(int))
values[i] = (v as List<int>).First();
else if(pType == typeof(string))
values[i] = (v as List<string>).First();
}
else
{
values[i] = v;
}
}
dataTable.Rows.Add(values);
}
return dataTable;
}