所有
我正在尝试对我的选择列表项进行排序,然后在列表中添加默认列表项,例如“选择下面的项目”并通过方法返回该列表。我注意到列表没有被排序,因为看起来,从ReSharper所说的,我需要返回排序结果 - 所以我的方法没有返回排序列表。
有没有办法在方法中进行排序和预先添加?
这就是我所拥有的:
public static IEnumerable<SelectListItem> GetBuildingClubs(List<BuildingClub> localClubs, List<BuildingClub> psfyClubs)
{
var buildingClubList = new List<SelectListItem>();
IEnumerable<BuildingClub> allBuildingClubs = localClubs.Union(psfyClubs);
foreach (BuildingClub b in allBuildingClubs)
{
buildingClubList.Add(new SelectListItem
{
Value = b.MasterCustomerId,
Text = b.NewBuildingClubName
});
}
//Sort list
buildingClubList.OrderBy(c => c.Text);
//Prepend to sorted list
buildingClubList.Insert(0, new SelectListItem
{
Value = "",
Text = "Select an Item Below"
});
return buildingClubList;
}
答案 0 :(得分:4)
OrderBy
不会修改输入列表;它返回一个新的排序序列。您需要存储该序列并使用它来构建列表:
buildingClubList = buildingClubList.OrderBy(c => c.Text).ToList();
或者,在将项目添加到列表之前对项目进行排序:
IEnumerable<BuildingClub> allBuildingClubs = localClubs.Union(psfyClubs).OrderBy(b => b.NewBuildingClubName);