以下代码中缺少什么?我想按文字
对列表进行排序public SelectList MyList { get; set; }
MyList = new SelectList(new SelectListItem[] {
new SelectListItem {
Text = "Select Customer", Value = "", Selected = false
}
}.Concat(myList.GetAll().Select(x => new SelectListItem { Text = x.Customer.Name + " - " + x.Name, Value = x.ID.ToString() })), "Value", "Text", "0");
MyList = MyList .OrderBy(x => x.Text);
编译时我在最后一行有错误。
无法隐式转换类型 'System.Linq.IOrderedEnumerable'来 'System.Web.Mvc.SelectList'。存在显式转换(是你 错过演员?)
答案 0 :(得分:0)
只需在构造函数参数中移动OrderBy
即可。实际上,您可能希望将第一个元素保留在列表的开头,以便OrderBy
应该应用于Concat
。此外,我重构了代码,以便更容易理解正在发生的事情:
var items = myList
.GetAll()
.Select(
x => new SelectListItem {
Text = x.Customer.Name + " - " + x.Name,
Value = x.ID.ToString()
}
)
.OrderBy(x => x.Text);
var itemsWithInitialItem = new SelectListItem[] {
new SelectListItem {
Text = "Select Customer", Value = "", Selected = false
}
}
.Concat(items);
MyList = new SelectList(itemsWithInitialItem, "Value", "Text", "0");
答案 1 :(得分:0)
您正在尝试对SelectList
对象进行排序,因为它是一个列表。对SelectList
的来源进行排序。您可能希望从排序中排除第一个:
MyList = new SelectList(
new SelectListItem[] {
new SelectListItem {
Text = "Select Customer", Value = "", Selected = false
}
}.Concat(
myList.GetAll()
.Select(x => new SelectListItem { Text = x.Customer.Name + " - " + x.Name, Value = x.ID.ToString() })
.OrderBy(x => x.Text)
), "Value", "Text", "0");