【发布时间】:2015-11-17 12:31:42
【问题描述】:
我有如下的 IEnumerable 集合
IEnumerable<Customer> items = new Customer[]
{
new Customer { Name = "test1", Id = 999 },
new Customer { Name = "test2", Id = 989 }
};
我想使用密钥Id 获得价值
我尝试如下
public int GetValue(IEnumerable<T> items,string propertyName)
{
for (int i = 0; i < items.Count(); i++)
{
(typeof(T).GetType().GetProperty(propertyName).GetValue(typeof(T), null));
// I will pass propertyName as Id and want all Id propperty values
// from items collection one by one.
}
}
【问题讨论】:
-
你为什么不直接使用 Select 方法呢?它也是类型安全的。
-
items.Select(x=>x.Id)会这样做。你想达到什么目标? -
如果您想以“通用”方式执行此操作,您可以为您的方法提供一个 Func
选择器(谓词)而不是您的 propertyName参数,然后在linq where 子句。与您需要选择的内容相同。如果是整个T项目,则不需要特定的select,但如果只需要特定的属性,则传递另一个选择器函数(Func<T, whatever type>类型)
标签: c# ienumerable ienumerator