【问题标题】:C# Lambda with Generic class T [duplicate]具有通用类 T 的 C# Lambda [重复]
【发布时间】:2016-12-07 19:25:57
【问题描述】:

我有一堆 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

    }

}

【问题讨论】:

  • 您必须使用反射并建立一个Expression 才能在您的OrderByDescending 中使用。但是你这样做解决了什么问题?可能有更好的选择。
  • 您应该研究动态 linq - 它就是这样做的。
  • @juharr : "LINQ to Entities 无法识别方法 'System.Reflection.PropertyInfo GetProperty(System.String)' 方法,并且该方法无法转换为存储表达式。"
  • @DanielA.White:我会试试的
  • @DanielA.White 你是对的,我需要动态 LINQ。谢谢。

标签: c# generics lambda


【解决方案1】:

您可以使用反射来检查 colName 是否存在并获取其值。查看 MSDN 页面 - https://msdn.microsoft.com/en-us/library/mt656691.aspx

【讨论】:

  • 这仅适用于内存中的集合,而不适用于 OP 的数据库查询。
猜你喜欢
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
相关资源
最近更新 更多