gpt4 book ai didi

c# - 如何在匿名方法中使用 LINQ 获取单列

转载 作者:太空宇宙 更新时间:2023-11-03 19:11:02 25 4
gpt4 key购买 nike

如何使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com