我正在使用Linq填充下拉列表,而orderby子句似乎不起作用。
public List<Hello> getManagers()
{
var que = (from man in db.Table1
where man.Role == "Manager"
orderby man.Name
select new Hello
{
Managers = man.Name
}).Distinct().ToList();
return que;
}
控制器类:
public ActionResult Index()
{
rp = new RequestProcess();
ViewBag.ID = fillSelectedList("", "ID", rp);
ViewBag.Managers = fillSelectedList("", "Managers", rp);
return View(""); //View 1
}
public static List<SelectListItem> fillSelectedList(string selValue, string type, RequestProcess rp )
{
List<SelectListItem> list = new List<SelectListItem>();
SelectListItem obj = new SelectListItem();
if (type == "Managers") {
var tempList= rp.getManagers();
tempList.ForEach(x =>
{
obj = new SelectListItem();
obj.Text = x.Managers;
obj.Value = x.Managers;
obj.Selected = x.Managers == selValue ? true : false;
list.Add(obj);
});
}
return list;
}
我仍然收到未排序的列表。有修复程序吗?
答案 0 :(得分:3)
结果未排序,因为方法Distinct
不会返回排序的结果。相反,您需要做的是先呼叫Disctinct
,然后再呼叫OrderBy
:
var que = (from man in db.Table1
where man.Role == "Manager"
select new Hello
{
Managers = man.Name
}).Distinct() // <- First distinct ...
.OrderBy(x => x.Managers) // <- ... then order by
.ToList();
答案 1 :(得分:1)
如上面的答案中所述,您需要将结果排序在Distinct()
之后。
还要注意,您正在将 Lambda表达式和 LINQ混合到实体查询中……您可能需要考虑选择其中之一以保持一致性(尽管没有语法)如果将它们混合会出错)。这是使用lambda表达式的相同查询:
var que = _context.Table1
.Where(m => m.Role == "Manager")
.Select(h => new Hello { Managers = h.Name })
.Distinct()
.OrderBy(o => o.Managers)
.ToList();