我有以下功能问题在泛型列表<string>或String []数组转换为数据表
public static DataTable ToTable<T>(this IEnumerable<T> listItem)
{
//Return null if the list is empty
if (listItem == null || listItem.Count() == 0) return null;
//Gets the type of the object
var listType = listItem.First().GetType();
//Initialize a new datatable
var dataTable = new DataTable(listType.Name);
//Create the datatable column names and types
listType.GetProperties().ToList().ForEach(col => dataTable.Columns.Add(col.Name, col.PropertyType));
//Get the datatable column names
var dataTableColumnNames = dataTable.GetDatatableColumnNames();
listItem.ToList().ForEach(item =>
{
//create a new datarow
var dataRow = dataTable.NewRow();
dataTableColumnNames
.Where(propName => listType.GetProperty(propName) != null)
.ToList()
.ForEach(columnName =>
//Exception happens here in the next line
dataRow[columnName] = listType.GetProperty(columnName).GetValue(item, null));
//Add the row to the data table
dataTable.Rows.Add(dataRow);
});
//Commit the changes to the datatable
dataTable.AcceptChanges();
return dataTable;
}
它的伟大工程为Dictionary对象和泛型列表作为List<MyClass>
..但不是 List<string>
或string[]
。
对于那些我收到例外参数计数不匹配。
误差以
dataRow[columnName] = listType.GetProperty(columnName).GetValue(item, null));
未来什么是发生错误了吗?
请帮
我们是否需要猜测抛出异常的位置? – Jon 2011-04-08 06:46:59
您能更精确地精确定位代码中引发异常的位置吗? – 2011-04-08 06:47:57
我有更新..这是头痛在dataRow [columnName] = listType.GetProperty(columnName).GetValue(item,null));例如string [] strNames = {“Name1”,“Name2”,“Name3”,“Name4”,“Name5”,“Name6”}; strNames.ToTable();抛出异常 – learner 2011-04-08 06:48:03