[英]Get column Lists from non-generic IEnumerable using Reflection
我有一個采用通用IEnumerable並為每一列生成唯一值列表的方法。 不用說這很慢,我想這是由於使用了所有反射所致。 這是一些示例代碼:
private void PopulateReferenceMatrices(IEnumerable newValue)
{
Type t = newValue.GetType();
Type baseType = t.GetGenericArguments()[0];
PropertyInfo[] properties;
Dictionary<string, int> indexValues = new Dictionary<string, int>();
properties = baseType.GetProperties();
int numProperties = properties.Count();
ListValues = new List<object>[numProperties];
for (int i = 0; i < numProperties; i++)
{
indexValues.Add(properties[i].Name, i);
FilterValues[i] = new List<object>();
}
//populate values into array
foreach (dynamic da in newValue)
{
foreach (PropertyInfo d in properties)
{
Object property = d.GetValue(da);
ListValues[indexValues[d.Name]].Add(property);
}
}
}
我可以為每個屬性生成一個值列表,而無需逐行瀏覽IEnumerable並將每個屬性轉換為對象嗎?
有沒有更快的方法來對IEnumerable中的每個項目執行類似的操作?
public IList getRowValue(IEnumerable value, string propertyName)
{
value.Select(x => x.propertyName).ToList();
}
這里一個可能的問題是您傳遞的是一個可能與眾不同的對象的非泛型集合,因此,創建propertyInfo應該在循環內部,以確保您可以從對象中讀取該屬性。 如果確定非泛型集合內的所有對象都是同一類型,則可以從列表中的第一個對象(如果它至少具有一個實例)在循環外部讀取propertyInfo。
您可以嘗試此操作,請參見代碼中的注釋:
public static IList GetRowValue(IEnumerable value, string propertyName)
{
// create an arraylist to be the result
var result = new ArrayList();
// loop in the objects
foreach (var item in value)
{
// search for a property on the type of the object
var property = item.GetType().GetProperty(propertyName);
// if the property was found
if (property != null)
{
// read the property value from the item
var propertyValue = property.GetValue(item, null);
// add on the result
result.Add(propertyValue);
}
}
return result;
}
請參見集合中包含不同對象的工作示例: https ://dotnetfiddle.net/bPgk4h
該問題與IEnumerable或反射無關。 尚未在IEnumerable中填充數據,因此我正在填充矩陣進行了數千次數據庫調用。 解決該問題后,它將立即加載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.