C# 具有泛型类T的C Lambda

C# 具有泛型类T的C Lambda,c#,generics,lambda,C#,Generics,Lambda,我有很多POCO类,假设其中一个看起来像下面这样 class Person{ public string Name {get;set;} public int Age {get;set;} } 这是我的普通课 class Helper<T> where T:class{ public Func<IQueryable<T>, IOrderedQueryable<T>> GenerateOrderByExpress

我有很多POCO类,假设其中一个看起来像下面这样

class Person{
      public string Name {get;set;}
      public int Age {get;set;}
}
这是我的普通课

class Helper<T> where T:class{

    public  Func<IQueryable<T>, IOrderedQueryable<T>> GenerateOrderByExpression(string colName)
    {
    return x => x.OrderByDescending(y => y.colName);
    //colName = NAME can be here for class person, it can be the Age field or something else for some other classes
    //how do i become generic here, how can I be able to use which ever field i pass as colName

    }

}

您可以使用反射来检查colName是否存在并获取其值。查看MSDN页面-。

您必须使用反射并建立一个表达式,以便在OrderByDescending中使用。但这样做能解决什么问题呢?很可能有更好的替代方法。您应该研究动态linq-它就是这样做的。@juharr:linq to Entities无法识别“System.Reflection.PropertyInfo GetPropertySystem.String”方法,并且该方法无法转换为存储表达式。@DanielA.White:我会尝试that@DanielA.White你是对的,我需要动态LINQ。谢谢。这只适用于内存中的集合,而不像OP那样适用于数据库查询。