Csharp/C#教程:使用属性的名称构建OrderBy表达式分享


使用属性的名称构建OrderBy表达式

我试图通过MVC3中的WebGrid控件来支持排序,MVC3通过sort参数将模型上的属性名称传递给我的操作。

 public class Agent { public int Id { get; set; } public string Name { get; set; } } [HttpGet] public ActionResult Index(string sort = "Id", string sortdir = "ASC") { // Define the parameter that we are going to use in the OrderBy clause. var param = Expression.Parameter(typeof(Agent), "agent"); // Now we'll make our lambda function that returns the // property's value by it's name. var sortExpression = Expression.Lambda<Func>(Expression.Property(param, sort), param); var agents = entities.OrderBy(sortExpression).ToList(); var model = new PagedResult { CurrentPage = 1, PageCount = 1, PageSize = DefaultPageSize, Results = agents, RowCount = agents.Count }; return View(model); } 

当我尝试通过Name属性(类型为string对模型进行排序时,此代码有效。 但是,如果我尝试按Id排序,我会收到错误Expression of type 'System.Int32' cannot be used for return type 'System.Object'

你可以使用Expression.Convert来执行Boxing。

上述就是C#学习教程:使用属性的名称构建OrderBy表达式分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/936286.html

(0)
上一篇 2021年11月7日
下一篇 2021年11月7日

精彩推荐