[英]C# IList iteration
我有一個 IList,其中包含一個對象,該對象具有名稱、ID、位置、商店、人員和金額。 我不想通過為每個屬性編寫語句來檢索所有這些字段的值
前任。
IList<CutDetail> btiCollection;
btiCollection[0].Id
btiCollection[0].location
無論如何,我可以遍歷此列表並檢索其字段中的數據,而無需具體命名它們是什么? 任何援助將不勝感激。
如果要檢索項目的所有屬性的值,可以使用反射創建檢索屬性值的函數列表:
List<Person> people = new List<Person>();
people.Add(new Person() {Id = 3, Location = "XYZ"});
var properties = (from prop in typeof (Person).GetProperties(BindingFlags.Public | BindingFlags.Instance)
let parameter = Expression.Parameter(typeof (Person), "obj")
let property = Expression.Property(parameter, prop)
let lambda = Expression.Lambda<Func<Person, object>>(Expression.Convert(property, typeof(object)), parameter).Compile()
select
new
{
Getter = lambda,
Name = prop.Name
}).ToArray();
foreach (var person in people)
{
foreach (var property in properties)
{
string name = property.Name;
object value = property.Getter(person);
//do something with property name / property value combination.
}
}
也可以使用反射來檢索屬性值,但是如果您有一個非常長的列表/許多屬性,這會相當慢並且可能會變得引人注目。
使用List<CutDetail>
而不是IList<CutDetail>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.