构建基于子实体的属性的排序依据Lambda表达式 [英] Building an OrderBy Lambda expression based on child entity's property

查看:156
本文介绍了构建基于子实体的属性的排序依据Lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成LINQ 排序依据使用lambda表达式与实体作为字符串的列名的输入(在sortOn的变量条款)。

I'm trying to generate a LINQ OrderBy clause using lambda expressions with an input of the column name of an entity as a string (in the "sortOn" variable below).

下面的代码工作正常,像代码产生的lambda

The code below works fine for a sortOn value like "Code" generating the lambda

p => p.Code



不过,我也想排序子实体,其中拉姆达可能是

But I would also like to sort on a child entity, where the lambda might be

p => p.Category.Description



因此​​,在这种情况下,我只是想设置sortOn =范畴。说明,并有产生正确的lamdba表达。

So in this instance, I would just like to set sortOn = "Category.Description" and have the correct lamdba expression generated.

这可能吗? 。要做到这一点会受到欢迎的最好办法任何建议。

Is this possible? Any suggestions about the best way to do this would be welcomed.

此代码工作正常进行的简单情况:

This code works fine for the simple case:

var param = Expression.Parameter(typeof (Product), "p");

var sortExpression = Expression.Lambda<Func<Product, object>>(
    Expression.Property(param, sortOn), param);

if (sortAscending ?? true)
{
   products = products.OrderBy(sortExpression);
}
else
{
   products = products.OrderByDescending(sortExpression);
}



用例针对此问题正在显示的数据的网格和能够对数据进行排序,只需通过将列名被回服务器上排序。我想使解决方案通用的,但使用现在特定类型(产品中的例子)已经开始。

The use-case for this problem is displaying a grid of data and being able to sort the data, simply by passing the column name to be sorted on back to the server. I'd like to make the solution generic, but have started using a particular type (Product in the example) for now.

推荐答案

这将生成正确的lambda表达式:

This will generate proper lambda expression:

var sortOn = "Category.Description";
var param = Expression.Parameter(typeof(Product), "p");
var parts = sortOn.Split('.');

Expression parent = param;

foreach (var part in parts)
{
    parent = Expression.Property(parent, part);
}

var sortExpression = Expression.Lambda<Func<Product, object>>(parent, param);

这篇关于构建基于子实体的属性的排序依据Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆