I'm currently trying to convert an IEnumerable<T>
to a 2-dimensional array of type T2 using an extension method with generic types. You should also be able to choose which properties of T you want to include into that array.
Here's what I got so far:
public static T2[][] ToMultidimensionalArray<T, T2>(this IEnumerable<T> enumerable, int count, params string[] propNames)
{
IEnumerator<T> enumerator = enumerable.GetEnumerator();
T2[][] resultArray = new T2[count][];
int i = 0;
int arrLength = propNames.Length;
while (enumerator.MoveNext())
{
resultArray[i] = new T2[arrLength];
int j = 0;
foreach(string prop in propNames)
{
resultArray[i][j] = ((T)enumerator.Current).//How do I access the properties?
j++;
}
i++;
}
return resultArray;
}
I'm having a problem accessing the properties of enumerator.Current
within the foreach
-Loop.
I'm using .NET-Framework 4.0.
Any input would be greatly appreciated.
Thanks,
Dennis
In general, this problem can be solved using reflection:
public static T2[][] ToMultidimensionalArray<T, T2>(
this IEnumerable<T> enumerable,
int count,
params string[] propNames)
{
T2[][] resultArray = new T2[count][];
int i = 0;
int arrLength = propNames.Length;
foreach (var item in enumerable)
{
resultArray[i] = new T2[arrLength];
int j = 0;
foreach (string prop in propNames)
{
// Get the required property info using reflection
var propertyInfo = typeof(T).GetProperty(prop);
// Extract the getter method of the property
var getter = propertyInfo.GetGetMethod();
// Invoke the getter and get the property value
var value = getter.Invoke(item, null);
// Cast the value to T2 and store in the array
resultArray[i][j] = (T2) value;
j++;
}
i++;
}
return resultArray;
}
I understood the problem as having a T
s collection where these objects have properties of T2
type. The goal is to take the properties of each object and place them in a multidimensional array. Correct me if I'm wrong.
Do you mean (T2)typeof(T).GetProperty(prop).GetValue(enumerator.Current, null);
But I can't understand what you want. I don't think this method can work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.