在基于特定属性值的泛型方法中获取 IEnumerable

本文关键字:IEnumerable 获取 泛型方法 于特定 属性 | 更新日期: 2023-09-27 18:35:13

我不知道如何根据特定的属性值在泛型方法中获取IEnumerable<T>。这是我的代码:

public List<T> ReadByProperty<T>(string propName, object propValue)
    where T : class
{
    return base.repository.Query<T>().AsEnumerable()
               .Where(x => x.GetType()
                      .GetProperty(propName)
                      .GetValue(x, null) == propValue)
               .ToList();
}

下面是非泛型方法中的类似代码:

return base.repository.Query<Models.Role>().Where(w => w.UserId == 2).ToList();

在基于特定属性值的泛型方法中获取 IEnumerable<T>

您需要手动构建一个表达式并将其传递给Where

var paramExpr = Expression.Parameter(typeof(T));
var propExpr = Expression.Property(paramExpr, propName);
var eqExpr = Expression.Equal(propExpr, Expression.Constant(propValue));
var predicate = Expression.Lambda<Func<T, bool>>(eqExpr, paramExpr);
return base.repository.Query<T>()
           .Where(predicate).ToList();