使用Linq.Ex pression动态拉姆达访问嵌套的性质 [英] Access nested properties with dynamic lambda using Linq.Expression
问题描述
让我们假设我有两个类:
Let's assume that I have two classes:
class person
{
int ID
string name
Address address
}
class address
{
int ID
string street
string country
}
这些类都或多或少给出,它们通过NHibernate的映射是诚实的:)
These classes are more or less given, they are mapped via nHibernate to be honest :)
在一个网格( datatables.net 为基础),我想有一个类型无关的排序。
In a grid (datatables.net as base) I would like to have a type-independent sorting.
因此,我创建了一个lambda前pression:
Therefore I created a lambda expression:
var param = Expression.Parameter(typeof(T), typeof(T).Name);
var sortExpression = Expression.Lambda<Func<T, object>>
(Expression.Convert(Expression.Property(param, "Property to sort"), typeof(object)), param);
如果我通过人的T型和替换属性进行排序和名,它工作正常(创建了一个正确的拉姆达)。如果要排序的属性为address.street将无法正常工作,丢了我以下错误:
If I pass Person as Type T and replace the "Property to sort" with "name" it works fine (creates a correct lambda). If the Property to sort is "address.street" it won't work, throw me the following error:
Property 'address.street' is not defined for type 'person'
我只看到一个解决方案,到目前为止,但不太清楚......我想尝试拆分包含属性名称字符串(斯普利特)。
I see only one solution so far, but not clear enough... I would try to split the string which contains the Property-Name (split by .)
谁能给一个更好的解决方案?我需要的SORTEX pression添加到一个IQueryable对象 query.OrderBy(SORTEX pression)
。
Can anyone give a better solution? I need to add the sortExpression to an IQueryable object query.OrderBy(sortExpression)
.
不知道如果我的标题是明确的,请继续前进并加以纠正。
Not sure if my title is clear, please go ahead and correct it.
先谢谢了。
推荐答案
什么是不明确?
您必须拆分,然后使用:
You have to split it and then use:
Expression.Property(Expression.Property(param, "address"), "street")
这篇关于使用Linq.Ex pression动态拉姆达访问嵌套的性质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!