且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

IQueryable< T>扩展方法不起作用

更新时间:2021-09-08 07:24:47

尝试一下...(但是我不确定它会满足您的要求.)

Try this... (but I'm not sure it will do what you want.)

public static class Extensions
{ 
    public static IQueryable<T> Sort<T>(this IQueryable<T> query, 
                                             string sortField, 
                                             SortDirection direction) 
    { 
        if (direction == SortDirection.Ascending) 
            return query.OrderBy(s => s.GetType()
                                       .GetProperty(sortField)); 
        return query.OrderByDescending(s => s.GetType()
                                             .GetProperty(sortField)); 

    } 
} 

...通用参数应该在方法上,而不在类上.将其从Extensions<T>移至Sort<T>(将使您摆脱遇到的编译器错误.

... The generic parameter should be on the method and not on the class. Moving it from Extensions<T> to Sort<T>( would allow you to get rid of the compiler error you are having.

对于您要使用反射进行的操作,您将为orderby子句返回一个PropertyInfo对象.这很可能与所需的表达式树不兼容.您可能需要查看

As for what you are trying to do with reflection, you would be returning a PropertyInfo object for the orderby clause. This is most likely not compable with the expression tree that you want. You may want to look at Dynamic LINQ.