我正在尝试按组名对SelectListItems列表进行排序。我可以根据组应用组和排序,但我似乎无法更改首先出现的组。即使按组名排序,组“B”也始终显示在组“A”之前。
List<SelectListItem> locationList = new List<SelectListItem>(dynamicTypes.Where(p => p.DynamicTypeId == DynamicTypes.Areas && p.ParentTypeId != null).Select(p => new SelectListItem
{
Text = p.NameEnglish,
Value = p.Id.ToString()
}));
SelectListGroup groupA = new SelectListGroup();
groupA.Name = "A";
SelectListGroup groupB = new SelectListGroup();
groupB.Name = "B";
foreach(SelectListItem sel in locationList)
{
if (sel.Text == "Aylmer, east of Vanier" || sel.Text == "Aylmer, west of Vanier" || sel.Text == "Gatineau, east of Paiement" || sel.Text == "Gatineau, west of Paiement"
|| sel.Text == "Hull" || sel.Text == "Parc de la Montagne" || sel.Text == "Plateau")
{
sel.Group = groupA;
}
else
{
sel.Group = groupB;
}
}
locationList.OrderBy(p => p.Group.Name);
答案 0 :(得分:2)
OrderBy
没有排序,它会创建一个新列表作为返回值,因此您需要将其分配给变量才能使用它:
locationList = locationList.OrderBy(p => p.Group.Name);
此处原始locationList
将被排序列表覆盖。如果您需要原始列表,请使用新变量:
var sortedList = locationList.OrderBy(p => p.Group.Name);