【发布时间】:2016-05-13 18:41:34
【问题描述】:
我正在尝试使用扩展方法将List 转换为datatable。实现是:
扩展方法
public static class list2Dt
{
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
}
控制器
var noDups = firstTable.AsEnumerable()
.GroupBy(d => new
{
name = d.Field<string>("name"),
date = d.Field<string>("date")
})
.Where(d => d.Count() > 1)
.Select(d => d.First())
.ToList();
DataTable secondTable = new DataTable();
secondTable.Columns.Add("name", typeof(string));
secondTable.Columns.Add("date", typeof(string));
secondTable.Columns.Add("clockIn", typeof(string));
secondTable.Columns.Add("clockOut", typeof(string));
secondTable = list2Dt.ToDataTable(noDups);
我收到以下错误:
An exception of type 'System.Data.DuplicateNameException' occurred in System.Data.dll but was not handled in user code
Additional information: A column named 'Item' already belongs to this DataTable.
在线引发上述错误:
dataTable.Columns.Add(prop.Name);
谁能找到问题所在。
【问题讨论】:
-
你的问题是你在数据表中添加了 4 列,然后你调用 toDataTable 来尝试添加所有列
-
-
我错过了 - 好点
-
我可能错了,因为正确的术语不是我的强项,但我不认为这是一种扩展方法:O