1

一类:

public class Person
{
    public string Title;
    public string Name;
    public Int32 Age;
}

我有一个字符串列表

List<String> fields = new List<String>()
{
    "Title",
    "Age"
};

我现在想,给定上面的字符串列表,WriteLine 列出的字段,同时遍历 Person 对象列表。

var persons = new List<Person>();

//Populate persons

foreach(Person person in persons)
{
    //Print out Title and Age of every person (because Title and Age are listed in fields)
}

我试过的:

  • 我尝试过的工作,但似乎效率极低。我为每次迭代创建一个Dictionary<String, object>并将对象的每个字段分配给字典中的一个条目,然后仅通过将键与fields列表中的项目匹配来评估字典条目。
4

1 回答 1

2

奇怪的要求,你需要低效的反射,例如:

IEnumerable<PropertyInfo> properties = typeof(Person)
            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(p => fields.Contains(p.Name));

foreach (Person person in persons)
{
    foreach (PropertyInfo prop in properties)
        Console.WriteLine("{0}: {1}", prop.Name, prop.GetValue(person, null));
}

演示

我刚刚看到您可能正在寻找字段而不是属性。然后使用这个类似的代码:

IEnumerable<FieldInfo> fields = typeof(Person)
    .GetFields( BindingFlags.Public | BindingFlags.Instance)
    .Where(f => fieldNames.Contains(f.Name)); // fieldNames is your List<string>

foreach (Person person in persons)
{
    foreach (FieldInfo field in fields)
        Console.WriteLine("{0}: {1}", field.Name, field.GetValue(person));
}
于 2012-11-20T14:10:33.147 回答