2011-04-08 84 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