0

如何扩展动态 linq 类以使用排序字符串表示的排序顺序最后对空字符串进行排序?

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

所以结果是'A','B','C',''

像这样,但接受字符串排序表达式:

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);
}
4

0 回答 0