+-

我正在尝试使用扩展方法将列表转换为数据表.实现是:
扩展方式
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);
有人可以找到问题所在吗?
最佳答案
您的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();
点击查看更多相关文章
转载注明原文:名为“ Item”的列已属于此DataTable - 乐贴网