今天,我有一个可以工作的方法,该方法返回基于字符串属性名称的lambda表达式,即我传入“ Description”,并且它返回d => d.Description的lambda。这很好用,但是现在我需要给定包含点符号的字符串,返回一个lambda表达式,即我想传递“ Customer.Name”并获得d => d.Customer.Name的lambda表达式。下面是我已经创建的返回1级lambda的方法,但是我不确定如何将其更改为多级。
protected dynamic CreateOrderByExpression(string sortColumn)
{
var type = typeof (TEntity);
Type entityType = null;
if (type.IsInterface)
{
var propertyInfos = new List<PropertyInfo>();
var considered = new List<Type>();
var queue = new Queue<Type>();
considered.Add(type);
queue.Enqueue(type);
while (queue.Count > 0)
{
var subType = queue.Dequeue();
foreach (var subInterface in subType.GetInterfaces().Where(subInterface => !considered.Contains(subInterface)))
{
considered.Add(subInterface);
queue.Enqueue(subInterface);
}
var typeProperties = subType.GetProperties(
BindingFlags.FlattenHierarchy
| BindingFlags.Public
| BindingFlags.Instance);
var newPropertyInfos = typeProperties
.Where(x => !propertyInfos.Contains(x));
propertyInfos.InsertRange(0, newPropertyInfos);
if (propertyInfos.All(f => f.Name != sortColumn)) continue;
entityType = subType;
break;
}
}
if (entityType == null)
{
return null;
}
var parameter = Expression.Parameter(typeof (TEntity));
var memberExpression = Expression.Property(parameter, entityType, sortColumn);
var lambdaExpression = Expression.Lambda(memberExpression, parameter);
return lambdaExpression;
}
Run Code Online (Sandbox Code Playgroud)
创建这样的帮助方法(将在代码的底部使用):
LambdaExpression GetLambdaExpression(Type type, IEnumerable<string> properties)
{
Type t = type;
ParameterExpression parameter = Expression.Parameter(t);
Expression expression = parameter;
for (int i = 0; i < properties.Count(); i++)
{
expression = Expression.Property(expression, t, properties.ElementAt(i));
t = expression.Type;
}
var lambdaExpression = Expression.Lambda(expression, parameter);
return lambdaExpression;
}
Run Code Online (Sandbox Code Playgroud)
现在像这样使用它:
GetLambdaExpression(typeof(Outer), new[] { "InnerProperty", "MyProperty" });
Run Code Online (Sandbox Code Playgroud)
对于以下课程:
class Outer
{
public Inner InnerProperty { get; set; }
}
class Inner
{
public int MyProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我知道它可能更适合您的原始代码,但是我想您可以从这里开始(例如,将带点的字符串转换为数组)。而且我知道可以使用递归来完成,但是今天我头疼...