我堅持以下問題:如何IEnumerable的<T>列表轉換爲數據表在C#中
我通常使用下面的功能自定義的數據傳輸到數據表,但在這種情況下,輸入數據是列表構成的一類。我只需要在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;
}
總部設在卡拉答案我想下面的代碼,但它不承認p-型類型(類型或命名空間名稱「的p-型」找不到(是否缺少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();
}
UPDATE
我想這是不是最好的解決方案,因爲它不accep牛逼任何列表類型,但它是我能做的最好的:
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;
}
如果你已經寫了這個,那麼它不能太難以至少試一試,對吧? – nvoigt