如何使用 linq 表达式通过匿名方法获取单列。这是我的代码,它不起作用:
public IEnumerable<object> GetPropertyValues<T>(string propName) where T : class
{
return base.Query<T>().AsEnumerable()
.Where(x => x.GetType().GetProperty(propName).Name == propName)
.Select(x => x.GetType().GetProperty(propName).GetValue(x, null));
}
下面是非泛型方法的代码:
base.Query<Product>().Select(x => x.ProductName).AsEnumerable();
提前致谢。
最佳答案
这个条件是不正确的,因为当缺少属性 propName
时,它会崩溃,而不是返回 false
:
.Where(x => x.GetType().GetProperty(propName).Name == propName)
如果您想说“动态类型具有属性 propName
”,它的适当条件如下所示:
.Where(x => x.GetType().GetProperty(propName) != null)
请注意,仅当 T
的某些(但不是全部)子类具有所需属性 propName
时才需要这样做。如果该属性存在于 T
本身中,您可以预先获取属性,然后像这样执行其余的查询:
var theProp = typeof(T)..GetProperty(propName);
return base.Query<T>().AsEnumerable().Select(x => theProp.GetValue(x, null));
关于c# - 如何在匿名方法中使用 LINQ 获取单列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20588536/