A class:
public class Person
{
public string Title;
public string Name;
public Int32 Age;
}
I have a list of strings
List<String> fields = new List<String>()
{
"Title",
"Age"
};
I would now like to, given the above list of strings, WriteLine the listed fields while iterating through a list of Person objects.
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)
}
What I’ve Tried:
- What I’ve tried works, but it seems extremely inefficient. I create a
Dictionary<String, object>for every iteration and assign every field of the object to an entry in the dictionary and then only evaluate the dictionary entries by matching the keys to the items in thefieldslist.
Strange requirement, you need inefficient reflection, for example:
DEMO
I’ve only just seen that you’re probably looking for fields instead of properties. Then use this similar code: