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:
foreach loop, as you can't, in general, efficiently access an IEnumerable by index.GetProperties requires either BindingFlags.Static or .Instance in order to return anything.propertyInfos[j].GetValue, passing in the T-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:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With