I've got a list of person objects, and I want to be able to programmatically get an anonymous type that contains a subset of that object's properties. I've got a list of Person objects like: (VS 2010 .NET 4.0). Took it for granted, but yes, the Person data is persisted in a database.
var personList = new List<Person>()
{
new Person(){ PersonId=11, Weight=100, Race="Green", Height=230},
new Person(){ PersonId=22, Weight=110, Race="Blue", Height=130}
};
and based on a user selecting which particular properties they want to see I'd like to emulate
var query = from c in personList
select new
{
Weight = c.Weight,
Height = c.Height,
PersonId = c.PersonId
};
where in this situation the user from a user interface selected PersonId, Weight and Height as properites they wished to use to create a new anonymous type.
I've got the following code which will take a given take a print the property values to the screen of what a (simulated) user might choose:
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(Person));
var propList = new List<string>()
{
"PersonId","Weight","Height"
};
for (int i = 0; i < personList.Count; i++)
{
for (int j = 0; j < props.Count; j++)
{
if (propList.Contains(props[j].Name))
{
//properties added to object here..but can't return anonymous type from method....
Console.WriteLine(props[j].GetValue(personList[i]));
}
}
}
this prints 11, 100, 230 and 22, 110, 130 to the console.
What I'm trying to do is essentially recreate the code in var query...
but be able to pass a list of properties to the select new
portion of the query.