I have a list of user objects, and I want to be able to programmatically retrieve an anonymous type that contains a subset of the properties of this object. I have a list of Person objects such as: (VS 2010.NET 4.0). Took it for granted, but yes, Person data is stored in the 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 the user who selects exactly which properties they want to see, I would 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 the user interface chose PersonId, Weight, and Height as the properties they wanted to use to create a new anonymous type.
I have the following code that takes the given print text onto the screen of what a (simulated) user can select:
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))
{
Console.WriteLine(props[j].GetValue(personList[i]));
}
}
}
11, 100, 230
22, 110, 130
.
, , , var query..., select new .