C#IList迭代

时间:2013-07-05 11:47:39

标签: c# visual-studio oop

我有一个IList,它包含一个具有字段名称,ID,位置,存储,人员和数量的对象。我不想通过为每个属性

编写语句来检索所有这些字段的值

离。

  IList<CutDetail> btiCollection;
  btiCollection[0].Id
  btiCollection[0].location

无论如何,我是否可以遍历此列表并检索其字段中的数据,而无需具体说明它们是什么?任何援助将不胜感激。

2 个答案:

答案 0 :(得分:2)

如果要检索项的所有属性的值,可以使用Reflection创建检索属性值的函数列表:

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.

    }
}

也可以使用反射检索属性值,但是如果你有一个很长的列表/很多属性,这个速度要慢很多,并且可能会变得很明显。

答案 1 :(得分:-2)

使用 List<CutDetail>代替IList<CutDetail>