当只知道属性的名称(甚至是子属性的名称)时,如何动态构建order-by表达式?
我想要达到的目标是:
dbResult = // some database-query as IQueryable<TSource> which is not yet executed;
if (!string.IsNullOrEmpty(request.OrderBy)) { // the user want's to group the results
var grouped = dbResult.GroupBy(/* this should be build dynamically */);
}
我需要一些东西,因为GroupBy
正在等待Func<TSource, TKey>
,但我在运行时只知道TKey
,可以是字符串,整数或者甚至是Guid。
用户可以将类似“Country.Name”的内容传递给request.OrderBy
属性,这意味着结果应按子属性(子选择)(国家/地区名称)进行分组。
我认为ExpressionTrees是去这里的方式,但是我甚至在开始之前就已经陷入困境,因为我不知道如何处理未知Type
以及通过子属性分组的选项-select /子属性。
答案 0 :(得分:0)
以下是如何动态构建LinearLayout rootView = null;
rootView = (LinearLayout) findViewById(R.id.rootView);
boolean isAttachedToWindow = ViewCompat.isAttachedToWindow(rootView);
表达式/查询:
GroupBy
问题在于没有好的通用方法来表示结果。使用非泛型public static class QueryableExtensions
{
public static IQueryable GroupByMember(this IQueryable source, string memberPath)
{
var parameter = Expression.Parameter(source.ElementType, "x");
var member = memberPath.Split('.')
.Aggregate((Expression)parameter, Expression.PropertyOrField);
var selector = Expression.Lambda(member, parameter);
var groupByCall = Expression.Call(typeof(Queryable), "GroupBy",
new Type[] { parameter.Type, member.Type },
source.Expression, Expression.Quote(selector));
return source.Provider.CreateQuery(groupByCall);
}
}
/ IQueryable
并不容易,因为几乎所有LINQ方法都在通用接口上运行。特别是对于IEnumerable
,您会发现需要创建越来越多这样的方法,因此您可以考虑使用Dynamic LINQ包。