I’m attempting to build a generic method that will convert any IEnumerable to an object[,]. The purpose of this is for insertion into excel via ExcelDNA which ideally requires 2d object arrays.
I am new to reflection and need some serious help to fill in the gaps here.
The code posted below is what I have so far, what I need will be to get the propertie of T at index i of DataSource in the outer loop. In the inner loop then get the values of each property in turn and insert into the object[,].
Any help appreciated.
Thanks
Richard
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;
}
}
You’re pretty close. A few pointers:
foreachloop, as you can’t, in general, efficiently access anIEnumerableby index.GetPropertiesrequires eitherBindingFlags.Staticor.Instancein order to return anything.propertyInfos[j].GetValue, passing in theT-instance you want to get it from and an array of indexer values – null for regular properties, but if your objects might have indexed properties you’ll either need to figure out something to pass here or handle an exception which might be thrown otherwise.I get something like this: