I am trying to build an ASP.NET page that sorts on nullable fields. What I want to do is, if there are null values in the sortable field, always throw those rows to the end of the list. Otherwise, they show up at the beginning of the list, and I can imagine pages and pages of null valued rows before you get to the A-Z sorted elements.
I am working in an ASP.NET framework. The solution for sortable columns is to build a dynamic query against the GridViewDataSource found here:
public static class QueryExtensions {
public static IQueryable<T> SortBy<T>(this IQueryable<T> source, string propertyName) {
if (source == null) {
throw new ArgumentNullException("source");
}
// DataSource control passes the sort parameter with a direction
// if the direction is descending
int descIndex = propertyName.IndexOf(" DESC");
if (descIndex >= 0) {
propertyName = propertyName.Substring(0, descIndex).Trim();
}
if (String.IsNullOrEmpty(propertyName)) {
return source;
}
ParameterExpression parameter = Expression.Parameter(source.ElementType, String.Empty);
MemberExpression property = Expression.Property(parameter, propertyName);
LambdaExpression lambda = Expression.Lambda(property, parameter);
string methodName = (descIndex < 0) ? "OrderBy" : "OrderByDescending";
Expression methodCallExpression = Expression.Call(typeof(Queryable), methodName,
new Type[] { source.ElementType, property.Type },
source.Expression, Expression.Quote(lambda));
return source.Provider.CreateQuery<T>(methodCallExpression);
}
}
Because I am working within this framework, I am not going to change the way that this function works. Instead, I am trying to overload the method with this signature:
public static IQueryable<T> SortBy<T>(this IQueryable<T> source, string propertyName, bool nullsToEnd)
The problem I am having is that I cannot figure out how to edit the 'methodName' to specifically allow for this type of sorting (A-Z with nulls at the end) to happen.
Any ideas as to what would do the trick?
Thanks