2012-10-03 42 views
3

我试图建立一个将所有的IEnumerable转换为对象的通用方法[,]。这样做的目的是通过ExcelDNA插入excel,理想情况下需要2d对象数组。转换IEnumerable的<T>反对[,] C#

我是新来思考,需要一些严重的帮助,以填补空白这里。 代码贴在下面是我到目前为止,我所需要的将是获得T的propertie在外环的DataSource的索引i。在内部循环中依次获取每个属性的值并插入到对象[,]中。

任何帮助表示赞赏。 感谢 理查德

public object[,] ConvertListToObject<T>(IEnumerable<T> DataSource) 
    { 
     int rows = DataSource.Count(); 

     //Get array of properties of the type T 
     PropertyInfo[] propertyInfos; 
     propertyInfos = typeof(T).GetProperties(BindingFlags.Public); 

     int cols = propertyInfos.Count(); //Cols for array is the number of public properties 

     //Create object array with rows/cols 
     object[,] excelarray = new object[rows, cols]; 

     for (int i = 0; i < rows; i++) //Outer loop 
     { 
      for(int j = 0; j < cols; j++) //Inner loop 
      { 
       object[i,j] =    //Need to insert each property val into j index 
      } 
     } 
     return excelarray; 
     } 
} 

回答

5

你是八九不离十。几个要点:

  • 外环将需要一个foreach循环,因为你不能在一般情况下,有效地索引访问IEnumerable
  • GetProperties需要BindingFlags.Static.Instance才能返回任何内容。
  • 您可以通过调用propertyInfos[j].GetValue传递T - 要从中获取它的实例以及索引器值数组 - 对于常规属性为null,但是如果您的对象可能具有索引属性,则需要实际值找出一些东西在这里传递或处理可能抛出的异常。

我得到的是这样的:

public object[,] ConvertListToObject<T>(IEnumerable<T> DataSource) 
{ 
    int rows = DataSource.Count(); 
    //Get array of properties of the type T 
    PropertyInfo[] propertyInfos; 
    propertyInfos = typeof(T).GetProperties(
     BindingFlags.Public | 
     BindingFlags.Instance); // or .Static 
    int cols = propertyInfos.Length; 
    //Create object array with rows/cols 
    object[,] excelarray = new object[rows, cols]; 
    int i = 0; 
    foreach (T data in DataSource) //Outer loop 
    { 
     for (int j = 0; j < cols; j++) //Inner loop 
     { 
      excelarray[i, j] = propertyInfos[j].GetValue(data, null); 
     } 
     i++; 
    } 
    return excelarray; 
} 
+0

对于文档'GetValue'说,第二个参数为空非索引属性。这将减少垃圾收集器的负担。 – phoog

+0

是啊,谢谢,我只是从你的回答中偷走了:) – Rawling

+0

够公平的,我从你的回答中偷了几个修复程序:-) – phoog

1

既然你不能索引到一个枚举,你应该枚举它在foreach循环而递增计数器,而不是使用一个for循环。

int i = 0; 
foreach (var row in DataSource) 
{ 
    for (int j = 0; j < cols; j++) 
     excelarray[i,j] = propertyInfos[j].GetValue(row, null); 
    i++; 
} 
+0

再次很好的答案。谢谢 –

1
public object[,] ConvertListToObject<T>(IEnumerable<T> dataSource) 
    { 
     if (dataSource != null) 
     { 
      var rows = dataSource.Count(); 
      var propertyInfos = typeof (T).GetProperties(BindingFlags.Public); 
      var cols = propertyInfos.Length; 
      var excelarray = new object[rows,cols]; 
      var i = 0; 
      foreach (var data in dataSource) 
      { 
       for (var j = 0; j < cols; j++) 
       { 
        excelarray[i, j] = propertyInfos[j].GetValue(data, null); 
       } 
       i++; 
      } 
      return excelarray; 
     } 
     return new object[,] {}; 
    } 
相关问题