Sort SelectList in specific order
Asked Answered
K

1

2

So I have a SelectList being generated in this method:

public static SelectList HolidayDays()
{
    SelectList retval = GenerateKeyValueList<HolidayCity>(HolidayCityHelper.GetFriendlyName, HolidayCity.NotSet);

    //sort list (NY, London....then the rest in order)


    return retval;
}

The GenerateKeyValueList<> method is defined here:

public static SelectList GenerateKeyValueList<T>(Func<T, string> nameGetter, T itemToNoInclude) where T : struct, IComparable, IConvertible
{
    List<SelectListItem> list = new List<SelectListItem>();

    var enumList = Enum.GetValues(typeof(T));

    foreach (var curr in enumList)
    {
        T t = (T)curr;
        if (t.Equals(itemToNoInclude) == false)
        {
            list.Add(new SelectListItem() { Text = nameGetter(t), Value = Convert.ToInt32(t).ToString() });
        }
    }
    return new SelectList(list, "Value", "Text");
}

In the first listed method, how do I sort the list as so in the comment. I want the list to have "New York" as the 1st element, "London" as the 2nd, and then the rest of the elements in alphabetical order.

Katiekatina answered 10/1, 2011 at 21:36 Comment(0)
U
3
list.OrderBy(i => i.Text == "New York")
    .ThenBy(i => i.Text == "London")
    .ThenBy(i => i.Text);

or you could write:

var items = from i in list
            orderby i.Text == "New York", i.Text == "London", i.Text descending
            select i;
Urita answered 10/1, 2011 at 21:42 Comment(1)
Can I do this on the SelectList item in the first method? i don't want to touch the convert method.Katiekatina

© 2022 - 2024 — McMap. All rights reserved.