问题
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