Sort SelectList in specific order

谁说我不能喝 提交于 2020-01-02 15:45:10

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/4651773/sort-selectlist-in-specific-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!