从string构造一个IOrderedQueryable <t>

时间:2017-09-23 05:29:26

标签: c# linq

我需要构造一个IOrderedQueryable来作为orderby语句应用,但我仍然坚持如何做到这一点,我给出了一个以逗号分隔的字符串字符串。

我可以遍历字符串并将字符串分解为各个部分,但我不知道我需要做什么才能将这些部分构建到IOrderedQueryable中。

        // the orderBy string is separated by ",", so we split it.
        var orderByAfterSplit = orderBy.Split(',');

        // apply each orderby clause in reverse order - otherwise, the 
        // IQueryable will be ordered in the wrong order
        foreach (var orderByClause in orderByAfterSplit.Reverse())
        {
            // trim the orderByClause, as it might contain leading 
            // or trailing spaces. Can't trim the var in foreach,
            // so use another var.
            var trimmedOrderByClause = orderByClause.Trim();

            // if the sort option ends with with " desc", we order
            // descending, otherwise ascending
            var orderDescending = trimmedOrderByClause.EndsWith(" desc");

            // remove " asc" or " desc" from the orderByClause, so we 
            // get the property name to look for in the mapping dictionary
            var indexOfFirstSpace = trimmedOrderByClause.IndexOf(" ");
            var propertyName = indexOfFirstSpace == -1 ?
                trimmedOrderByClause : trimmedOrderByClause.Remove(indexOfFirstSpace);

            // HERE IS MY PROBLEM
            // what needs to be here?
        }

有人可以帮忙吗?

orderBy字符串的示例可能是

  • 名称
  • name desc
  • 名,代码
  • 名称,代码desc,值

1 个答案:

答案 0 :(得分:0)

public static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
{
    string[] props = property.Split('.');
    Type type = typeof(T);
    ParameterExpression arg = Expression.Parameter(type, "x");
    Expression expr = arg;
    foreach (string prop in props)
    {
        PropertyInfo pi = type.GetProperty(prop);
        if (pi == null)
            pi = type.GetProperties().FirstOrDefault(x => x.Name.ToLower() == prop.ToLower());
        expr = Expression.Property(expr, pi);
        type = pi.PropertyType;
    }
    Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
    LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);

    object result = typeof(Queryable).GetMethods().Single(
        method => method.Name == methodName
        && method.IsGenericMethodDefinition
        && method.GetGenericArguments().Length == 2
        && method.GetParameters().Length == 2)
        .MakeGenericMethod(typeof(T), type)
        .Invoke(null, new object[] { source, lambda });
    return (IOrderedQueryable<T>)result;
}

ApplyOrder(source, property, "OrderBy");
ApplyOrder(source, property, "OrderByDescending")
ApplyOrder(source, property, "ThenBy");
ApplyOrder(source, property, "ThenByDescending");