C# MVC: Func<Table1, "runtime type"> How do I get a dynamic type?
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!
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:
Type funcType = typeof(Func<,>).MakeGenericType(typeof(Table1), columnType);
Expression.Lambda(funcType, memberExp, new ParameterExpression[] { param });
精彩评论