我有一个人对象列表,希望能够编程获取一个匿名类型,其中包含该对象的一部分属性。我有一个Person对象列表,如下:(VS 2010 .NET 4.0)。请注意,Person数据存储在数据库中。
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}
};
基于用户选择要查看的特定属性,我想模拟
var query = from c in personList
select new
{
Weight = c.Weight,
Height = c.Height,
PersonId = c.PersonId
};
在这种情况下,用户从用户界面中选择了PersonId、Weight和Height作为他们想要用来创建新的匿名类型的属性。
我有以下代码,将会打印出一个(模拟)用户可能选择的属性的属性值:
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]));
}
}
}
这段代码将会在控制台打印出11、100、230以及22、110、130。
我想要做的就是基本上重建var query...
中的代码,但是能够向查询的select new
部分传递一列表格。