动态Linq OrderBy null错误

时间:2013-08-09 13:45:48

标签: c# linq dynamic null sql-order-by

我正在使用动态Linq来根据传入的列来对结果集进行排序。当用户点击表列时,我正在使用它来命令表。

如果属性即时排序是一个null为null的类,代码会失败,我希望能够通过字符串动态排序,但如果属性是类,则可以满足空值。

这是使用./ / p>的System.Linq.Dynamic类的代码

public static IQueryable OrderBy(this IQueryable source, string ordering,
    params object[] values)
{
    if (source == null) { throw new ArgumentNullException("source"); }
    if (ordering == null) { throw new ArgumentNullException("ordering"); }

    ParameterExpression[] parameters = new ParameterExpression[1]
    {
        Expression.Parameter(source.ElementType, "")
    };

    IEnumerable<DynamicOrdering> enumerable = new ExpressionParser(
        parameters, ordering, values).ParseOrdering();

    Expression expression = source.Expression;
    string str1 = "OrderBy";
    string str2 = "OrderByDescending";

    foreach (DynamicOrdering dynamicOrdering in enumerable)
    {
        expression = (Expression) Expression.Call(typeof (Queryable),
            dynamicOrdering.Ascending ? str1 : str2, new Type[2]
        {
            source.ElementType,
            dynamicOrdering.Selector.Type
        }, new Expression[2]
        {
            expression,
            (Expression) Expression.Quote((Expression) Expression.Lambda(
                dynamicOrdering.Selector, parameters))
        });
        str1 = "ThenBy";
        str2 = "ThenByDescending";
    }
    return source.Provider.CreateQuery(expression);
}

并像这样调用它

if (property.PropertyType == typeof(Sitecore.Data.Items.Item))
{
    orderByProperty = property.Name + ".Name";
}
else
{
    orderByProperty = property.Name;
}

return tableOrder == TableOrder.az
    ? projects.OrderBy(orderByProperty + " ascending").ToList()
    : projects.OrderBy(orderByProperty + " descending").ToList();

该属性有时是一个类,如果是这种情况,我希望能够通过类上名为name的字段对其进行排序。上面的代码可以工作,但如果属性是一个类并且为null,那么它就会失效。

如何按字段排序并在最后包含空项?

1 个答案:

答案 0 :(得分:1)

我找到了答案。使用以下替换System.Linq.Dynamic.DynamicQueryable类中的OrderBy查询。它将处理作为对象的属性中的空值。

public static IQueryable OrderBy(this IQueryable source, string ordering,
    params object[] values)
{
    //This handles nulls in a complex object
    var orderingSplit = ordering.Split(new char[] {' '},
        StringSplitOptions.RemoveEmptyEntries);
    var sortField = orderingSplit[0];
    var splitted_sortField = sortField.Split(new char[] { '.' }, 
        StringSplitOptions.RemoveEmptyEntries);

    if (splitted_sortField.Length > 1)
    {
        sortField = "iif(" + splitted_sortField[0] + "==null,null," + sortField + ")";
    }
    ordering = orderingSplit.Length == 2
       ? sortField + " " + orderingSplit[1]
       : sortField;

    if (source == null) throw new ArgumentNullException("source");
    if (ordering == null) throw new ArgumentNullException("ordering");

    ParameterExpression[] parameters = new ParameterExpression[] {
        Expression.Parameter(source.ElementType, "") };
    ExpressionParser parser = new ExpressionParser(parameters, ordering, values);
    IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
    Expression queryExpr = source.Expression;
    string methodAsc = "OrderBy";
    string methodDesc = "OrderByDescending";

    foreach (DynamicOrdering o in orderings)
    {
        queryExpr = Expression.Call(
            typeof(Queryable), o.Ascending ? methodAsc : methodDesc,
            new Type[] { source.ElementType, o.Selector.Type },
            queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters)));
        methodAsc = "ThenBy";
        methodDesc = "ThenByDescending";
    }
    return source.Provider.CreateQuery(queryExpr);
}

从此处获取代码并将其直接烘焙到Dynamic Linq函数中。

Null Reference Exception in a Dynamic LINQ Expression