C# Linq OrderBy 过滤 null 或空值使其排在最后。

19 浏览
0 Comments

C# Linq OrderBy 过滤 null 或空值使其排在最后。

我尝试创建一个自定义的orderby扩展方法,我的代码已经成功运行,但我还想在结果中将null、空或零值列在最后,有人可以帮我解决这个问题吗?

以下是我的orderby扩展方法的代码:

public static IQueryable OrderBy(this IQueryable q, string SortField, bool isAsc)
{
    var param = Expression.Parameter(typeof(T), "p");
    var prop = Expression.Property(param, SortField);
    var exp = Expression.Lambda(prop, param);
    string method = isAsc ? "OrderBy" : "OrderByDescending";
    Type[] types = new Type[] { q.ElementType, exp.Body.Type };
    var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
    return q.Provider.CreateQuery(mce);
}

提前感谢您的帮助。

0