不能隐式转换类型'System.Linq.IOrderedEnumerable
本文关键字:System IOrderedEnumerable Linq Web Mvc 转换 类型 不能 | 更新日期: 2023-09-27 18:08:07
我在以下代码中缺少什么?我想按Text
排序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);
我在编译时在最后一行出现错误。
不能隐式转换类型"来。IOrderedEnumerable"System.Web.Mvc.SelectList"。存在显式转换(是吗?)
您正在尝试排序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");
将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");
本文关键字:System IOrderedEnumerable Linq Web Mvc 转换 类型 不能 | 更新日期: 2023-09-27 18:08:07
我在以下代码中缺少什么?我想按Text
排序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);
我在编译时在最后一行出现错误。
不能隐式转换类型"来。IOrderedEnumerable"System.Web.Mvc.SelectList"。存在显式转换(是吗?)
您正在尝试排序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");
将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");