コード例 #1
0
        public static IOrderedQueryable <T> ThenByDescending <T>(this IOrderedQueryable <T> query, String path)
        {
            Type currentType = typeof(T);

            String[] parts = path.Split(',');

            foreach (String part in parts)
            {
                PropertyInfo propInfo = currentType.GetProperty(part);
                Type         propType = propInfo.PropertyType;
                String       propFetchFunctionName = "ThenByDescending";
                Type         delegateType          = typeof(Func <,>).MakeGenericType(currentType, propType);

                ParameterExpression exprParam  = Expression.Parameter(currentType, "it");
                MemberExpression    exprProp   = Expression.Property(exprParam, part);
                LambdaExpression    exprLambda = Expression.Lambda(delegateType, exprProp, new ParameterExpression[] { exprParam });

                Type orderExtensionMethodsType = typeof(Queryable);

                List <Type> fetchMethodTypes = new List <Type>();
                fetchMethodTypes.AddRange(query.GetType().GetGenericArguments().Take(2));
                fetchMethodTypes.Add(propType);

                MethodInfo fetchMethodInfo = orderExtensionMethodsType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod).Where(x => x.Name == propFetchFunctionName && x.GetParameters().Length == 2).Single();
                fetchMethodInfo = fetchMethodInfo.MakeGenericMethod(fetchMethodTypes.ToArray());

                Object[] args = new Object[] { query, exprLambda };

                query = fetchMethodInfo.Invoke(null, args) as IOrderedQueryable <T>;

                currentType = propType;
            }

            return(query);
        }