My project is having some user defined linq extension methods for orderby, ThenBy etc. And I want to sort a list of object based on a string property in that object by ignoring its case.
Code:
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;
}
But at the end I'm receiving an exception:
Static members = error CS0119: 'NotSupportedException' is a type, which is not valid in the given context
I think, it is expecting Enumerable source instead of Queryable. But I can't change source type. How can I resolve this?