0

How can extend the dynamic linq class to sort empty strings last in the sort order using a sort string expressing?

query.OrderNullsLast("Col1 ASC, Col2 DESC, Col3 ASC")

So the result is 'A', 'B', 'C', ''

Something like this, but accepting a string sort expression:

public static IQueryable<TSource> OrderByNullsLast<TSource, TKey>(
      this IQueryable<TSource> query, Expression<Func<TSource, TKey>> keySelector)
{
      return query.OrderBy(keySelector).NullsLast(keySelector);
}

public static IQueryable<TSource> NullsLast<TSource, TKey>(
      this IQueryable<TSource> query, Expression<Func<TSource, TKey>> keySelector)
{
      var nullExpr = Expression.Constant(null, typeof(TKey));
      var equalExpr = Expression.Equal(keySelector.Body, nullExpr);
      var lambda = Expression.Lambda<Func<TSource, bool>>(equalExpr, keySelector.Parameters);
      return query.OrderBy(lambda);
}
Jon.ee
  • 95
  • 2
  • 8

0 Answers0