C# MVC:Func如何获得动态类型?
嘿,我正在尝试根据用户单击的内容对列的自定义数据网格进行排序。变量“sort”被传递到控制器,但它只是一个字符串,说明要对哪一列进行排序。
我需要获取要在 LambdaExpression 中使用的该列的类型...这是代码,
ParameterExpression param = Expression.Parameter(typeof(Table1), "x");
MemberExpression memberExp = Expression.Property(param, sort);
var lambdaExp = Expression.Lambda<Func<Table1, int>>(memberExp, new ParameterExpression[] { param });
if (bool.Parse(Session["sort"].ToString()))
sortedKeys = keys.OrderBy(lambdaExp).Skip((currentPage - 1) * _pageSize).Take(_pageSize);
else
sortedKeys = keys.OrderByDescending(lambdaExp).Skip((currentPage - 1) * _pageSize).Take(_pageSize);
正如您在第 3 行中看到的那样,我传递了委托 Func 用于具有 int 类型的列,但这将根据单击的列动态更改。
我该如何解决这个问题?
谢谢!
Hey, I'm trying to sort a custom data grid of columns based on what the user clicked. The variable "sort" is being passed to the controller but is just a string saying what column is to be sorted.
I need to get the Type of that column to be used in a LambdaExpression... heres the code
ParameterExpression param = Expression.Parameter(typeof(Table1), "x");
MemberExpression memberExp = Expression.Property(param, sort);
var lambdaExp = Expression.Lambda<Func<Table1, int>>(memberExp, new ParameterExpression[] { param });
if (bool.Parse(Session["sort"].ToString()))
sortedKeys = keys.OrderBy(lambdaExp).Skip((currentPage - 1) * _pageSize).Take(_pageSize);
else
sortedKeys = keys.OrderByDescending(lambdaExp).Skip((currentPage - 1) * _pageSize).Take(_pageSize);
As you can see on line #3 where I pass the delegate Func works from for a column that has a Type of int, but that will change dynamically depending on what column was clicked.
How do I solve this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您有方便的列类型,它将是 System.Type。我们称之为“columnType”。所以你想要做的是使用非泛型 Lambda 方法:
I assume you have the column type handy, which will be a System.Type. Let's call it "columnType". So what you'd want to do is use the non-generic Lambda method: