Question

All,

I am trying to sort my selectlist items and then prepend a default list item to the list, something like "Select an Item Below" and return that list via a method. I noticed that the list is not being sorted because it looks like, from what ReSharper is saying, I need to return the sorted result - so my method is not returning a sorted list.

Is there a way to do the sorting and prepending in the method?

Here is what I have:

       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;

    }
Était-ce utile?

La solution

OrderBy doesn't modify the input list; it returns a new sorted sequence. You need to store that sequence and use it to build your list:

buildingClubList = buildingClubList.OrderBy(c => c.Text).ToList();

Alternatively, sort the items before you add them to the list:

IEnumerable<BuildingClub> allBuildingClubs = localClubs.Union(psfyClubs).OrderBy(b => b.NewBuildingClubName);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top