1

I'm using a generic method to sort an IQueryable collection which uses the Queryable.OrderBy and LambdaExpression methods:

public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, IEnumerable<SortParameter> sortParameters)
{
    IOrderedQueryable<T> sourceOrderedQueryable = sortParameters[0].SortDirection == ListSortDirection.Ascending
            ? Queryable.OrderBy(source, (dynamic)CreateExpression<T>(sortParameter[0].ParameterName))
            : Queryable.OrderByDescending(source, (dynamic)CreateExpression<T>(sortParameter[0].ParameterName));

    // ... Same with Queryable.ThenBy

    return sourceOrderedQueryable;
}

private static LambdaExpression CreateExpression<T>(string propertyName)
{
    var modelParameter = Expression.Parameter(typeof(T), "t");
    Expression body = Expression.PropertyOrField(modelParameter, sortParameter);
    return Expression.Lambda(body, modelParameter);
}


query.OrderBy(sortParameters)   // for ProductId sortParameter (string type in db) should sort as int

This works fine but I have to parse one column from the sorted model from string to int, something like:

OrderBy(x => Convert.ToInt32(x.ProductId))

I have no idea how to integrate the above conversion into this generic mechanism and the lambda expression for a specific case. Is it possible for this mechanism to converting one column (property) type?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
EmilOS
  • 15
  • 6
  • See maybe it helps you: https://stackoverflow.com/questions/5984919/convert-string-to-int-for-ordering-using-linq – Nika Jul 24 '22 at 20:02
  • 1
    Try something like followingt : OrderBy(x => ProductId.ToCharArray().All(y => char.IsDigit()) ? x.Convert.ToInt32(ProductId) : ProductId) – jdweng Jul 24 '22 at 22:31
  • 1
    From your code I see that you are not so familiar with Expression Tree building. Try to use this extension [ApplyOrderBy](https://stackoverflow.com/a/65850085/10646316) instead. – Svyatoslav Danyliv Jul 25 '22 at 04:36
  • Thanks for help, I changed that Expression Tree – EmilOS Jul 26 '22 at 10:29

0 Answers0