2011-04-08 33 views
0

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

未來什麼是發生錯誤了嗎?

請幫

+0

我們是否需要猜測拋出異常的位置? – Jon 2011-04-08 06:46:59

+0

您能更精確地精確定位代碼中引發異常的位置嗎? – 2011-04-08 06:47:57

+0

我有更新..這是頭痛在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

回答

0

這裏的交易。當使用反射時,索引運算符實際上被認爲是一個屬性,因此參數計數不匹配。

如果您打入代碼並檢查GetProperties()實際枚舉的屬性,您將看到「Chars」屬性。這是字符串的索引操作符。由於您沒有提供索引,因此會出現「參數計數不匹配」錯誤。

實際上,我假定字符串沒有任何要放入數據表的屬性,而是字符串實例是你想要放入數據表中的。

您可以創建一個模型來存儲字符串,並將字符串作爲模型的屬性,然後該字符串將與當前的代碼一起存儲。否則,您將需要重新考慮用於基元類型的表生成算法。

我希望這有助於:)

0

由於string公共屬性之一是索引和傳遞null作爲指標值。所以你最終會這樣做:string[null]最終會出現異常。

我還沒有驗證過,因爲我現在沒有VS可用,所以我可能是錯的,但我很確定這就是問題所在。

更新:這個問題回答如何檢測索引屬性:C# Reflection Indexed Properties

相關問題