如何在自定义Linq扩展方法中使用StringComparer?

时间:2018-07-19 08:44:22

标签: c# linq linq-to-entities

说明:

我的项目正在为orderby,ThenBy等提供一些用户定义的linq扩展方法。我想通过忽略对象的大小写,基于该对象中的字符串属性对对象列表进行排序。

代码:

public static IOrderedQueryable<TEntity> OrderUsingSortExpression<TEntity>(this IQueryable<TEntity> source, string sortExpression) where TEntity : class
        {
            OrderedQueryable<TEntity> result = null;
            try
            {
                  result =  source.OrderBy("Title") 
                    // I'm getting an exception here in result.

            }
            catch (Exception ex)
            {
               result = source as IOrderedQueryable<TEntity>;
            }
            return result;
        }

    public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string fieldName) where TEntity : class


     {
            MethodCallExpression resultExp = GenerateMethodCall<TEntity>(source, "OrderBy", fieldName);
            return source.Provider.CreateQuery<TEntity>(resultExp) as IOrderedQueryable<TEntity>;
        }
    private static MethodCallExpression GenerateMethodCall<TEntity>(IQueryable<TEntity> source, string methodName, String fieldName) where TEntity : class
            {
                Type type = typeof(TEntity);
                Type selectorResultType;
                var StrComp = StringComparer.OrdinalIgnoreCase;
                LambdaExpression selector = GenerateSelector<TEntity>(fieldName, out selectorResultType);
                MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName,
                                new Type[] { type, selectorResultType },
                                source.Expression, Expression.Quote(selector), Expression.Constant(StrComp));
                return resultExp;
            }

但是最后,我收到一个异常“静态成员=错误CS0119:'NotSupportedException'是一种类型,在给定的上下文中无效”

我认为,它期望使用Enumerable源而不是Queryable。但是我无法修改源类型。

您能提出任何解决方案吗?

0 个答案:

没有答案
相关问题