我有以下功能問題在泛型列表<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