C# 如何动态创建包含点符号的Lambda表达式
我现在有一个方法可以根据字符串属性名返回lambda表达式,即传入“Description”,然后返回d=>d.Description的lambda。这很好,但是现在我需要返回一个lambda表达式,给定一个包含点符号的字符串,即我想传递“Customer.Name”,并得到一个lambda表达式,返回d=>d.Customer.Name。下面是我已经创建的返回1级lambda的方法,但我不确定如何将其更改为多级C# 如何动态创建包含点符号的Lambda表达式,c#,dynamic,lambda,C#,Dynamic,Lambda,我现在有一个方法可以根据字符串属性名返回lambda表达式,即传入“Description”,然后返回d=>d.Description的lambda。这很好,但是现在我需要返回一个lambda表达式,给定一个包含点符号的字符串,即我想传递“Customer.Name”,并得到一个lambda表达式,返回d=>d.Customer.Name。下面是我已经创建的返回1级lambda的方法,但我不确定如何将其更改为多级 protected dynamic CreateOrderByExpression
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;
}
受保护的动态CreateOrderByExpression(字符串sortColumn)
{
变量类型=类型(强度);
类型entityType=null;
if(类型IsInterface)
{
var propertyInfos=新列表();
var=newlist();
var queue=新队列();
添加(类型);
队列。排队(类型);
而(queue.Count>0)
{
var subType=queue.Dequeue();
foreach(子类型.GetInterfaces()中的变量子接口,其中(子接口=>!考虑过的。包含(子接口)))
{
添加(子接口);
排队(子接口);
}
var typeProperties=subType.GetProperties(
BindingFlags.FlatterHierarchy
|BindingFlags.Public
|BindingFlags.Instance);
var newPropertyInfos=类型属性
其中(x=>!propertyInfos.Contains(x));
propertyInfos.InsertRange(0,newPropertyInfos);
如果(propertyInfos.All(f=>f.Name!=sortColumn))继续;
entityType=子类型;
打破
}
}
if(entityType==null)
{
返回null;
}
var参数=表达式参数(typeof(tenty));
var memberExpression=Expression.Property(参数、entityType、sortColumn);
var lambdaExpression=Expression.Lambda(memberExpression,参数);
返回lambdaExpression;
}
创建这样的助手方法(用于代码的底部):
对于以下类别:
class Outer
{
public Inner InnerProperty { get; set; }
}
class Inner
{
public int MyProperty { get; set; }
}
我知道它可能更适合您的原始代码,但我想您可以从这里开始(比如将带点的字符串转换为数组)。我知道可以用递归实现,但我今天头疼
GetLambdaExpression(typeof(Outer), new[] { "InnerProperty", "MyProperty" });
class Outer
{
public Inner InnerProperty { get; set; }
}
class Inner
{
public int MyProperty { get; set; }
}