[英]Convert IEnumerable<T> to object[,] C#
我正在嘗試構建一個將任何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;
}
}
你很親密。 幾點建議:
foreach
循環,因為通常不能通過索引有效地訪問IEnumerable
。 GetProperties
需要BindingFlags.Static
或.Instance
才能返回任何內容。 propertyInfos[j].GetValue
獲取實際值,傳入propertyInfos[j].GetValue
中獲取的T
-instance和一組索引器值 - 對於常規屬性為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;
}
由於您無法索引到可枚舉,因此您應該在遞增計數器時在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++;
}
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[,] {};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.