我正在尝试使用扩展方法将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);
有人能找到问题所在。
答案 0 :(得分:3)
您的ToDataTable
方法需要一个对象列表 - 很可能是一个简单的DTO或类似的列表。
您正在向其传递DataRow
个实例的列表,其中该类有多个overloads of property Item
,这意味着当您尝试构建新的DataTable
时,它会尝试添加名称为Item
的多个列,这些列在DataTable
中无效。
在此过程中,将noDups
投影到新对象,而不是保留DataRow
:
public class MyClass
{
public string Name{get;set;}
public string Date{get;set;}
}
var noDups = firstTable.AsEnumerable()
.GroupBy(d => new
{
name = d.Field<string>("name"),
date = d.Field<string>("date")
})
.Where(d => d.Count() > 1)
.Select(d => {
var first = d.First();
return new MyClass()
{
Name = (string)first["name"],
Date = (string)first["date"]
}
})
.ToList();