1

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

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

这是我使用的 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,那么它就会失败。

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

4

1 回答 1

1

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

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

Null Reference Exception in a Dynamic LINQ Expression

于 2013-08-12T09:15:44.600 回答