将IEnumerable <T>转换为object [,] C#

Ric*_*odd 3 c# generics reflection

我正在尝试构建一个将任何IEnumerable转换为对象[,]的泛型方法.这样做的目的是通过ExcelDNA插入excel,理想情况下需要2d对象数组.

我是新思考的人,需要一些认真的帮助来填补这里的空白.下面发布的代码是我到目前为止所需要的,我需要的是在外部循环中获取DataSource的索引i处的T属性.在内部循环中,然后依次获取每个属性的值并插入到对象[,]中.

任何帮助赞赏.谢谢理查德

    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;
       }
}
Run Code Online (Sandbox Code Playgroud)

Raw*_*ing 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;
}
Run Code Online (Sandbox Code Playgroud)