T 是一种可能有也可能没有特定属性的类型,比如说“City”。对于具有名为“City”的属性的类型,我想限制记录,以便仅返回 Gotham 的居民并对其进行排序。
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values)
{
var type = typeof(T);
var property = type.GetProperty(ordering);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
MethodCallExpression resultExp = Expression.Call(
typeof(Queryable),
"OrderBy",
new Type[] { type, property.PropertyType },
source.Expression,
Expression.Quote(orderByExp));
string propertyToRestrictOn = "City";
string restrictedValue = "Gotham";
var restrictedProperty = type.GetProperty(propertyToRestrictOn);
if(null ! = restrictedProperty )
{
// TODO: What to add here so than only those records are returned that have a
// property named City and the value is 'Gotham'???
}
return source.Provider.CreateQuery<T>(resultExp);
}
如果可能的话,请在此处命名/链接一些有用的文献,以防我必须创建更复杂的查询,即混合和/或
该代码是从How do I apply OrderBy on an IQueryable using a string column name in a generic extension method?借来的 ?