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

标签 c# linq anonymous-methods

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

相关文章:

c# - 为什么 C# 的二元运算符总是返回 int 而不管其输入格式如何?

c# 使用 EPPLUS 使工作表名称只读?

multithreading - 我可以将 Delphi TThread.Synchronize() 本地移动到 VCL 表单以从主线程或工作线程调用吗?

Delphi:强制捕获匿名方法的 "unused"变量

C# Lotus Notes - 多个 .nsf 文件

c# - 如何将我的 asp.net 项目发布到本地 iis?

c# - 如何映射两个不同类型的表达式?

c# - 转换为 LINQ To Entity 查询中的类型

linq - LINQ 中的更新查询包含 WHERE 子句中的所有列,而不仅仅是主键列

delphi - 有人可以向我解释一下匿名方法吗?