动态Linq OrderBy为空错误 [英] Dynamic Linq OrderBy null error

查看:111
本文介绍了动态Linq OrderBy为空错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using dynamic Linq to order a result set depending on which column is passed in. I'm using this to order a table when a user clicks on a table column.

如果排序时使用的属性是一个空类,则代码将失效,我希望能够按字符串动态排序,但如果该属性是一个类,则可满足空值.

If the property im ordering on is a class which is null the code falls over, i want to be able to dynamically orderby a string but cater for nulls if the property is a class.

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

This is the code from the System.Linq.Dynamic class im using.

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,则它将失败.

the property is sometimes a class, if this is the case i want to be able to order it by a field called name on the class. The above code works but if the property is a class and null then it falls over.

如何按字段排序并在末尾添加空项目?

How do I order by a field and have the null items at the end?

推荐答案

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

I've found the answer. Replace the OrderBy query in the System.Linq.Dynamic.DynamicQueryable class with the below. It will handle nulls in a property that is an object.

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函数中.

Taken the code from here and baked it directly into the Dynamic Linq function.

动态LINQ表达式中的空引用异常

这篇关于动态Linq OrderBy为空错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆