I have this code
List<SelectListItem> list = new List<SelectListItem>()
{
new SelectListItem() { Text = "bob", Value = "bob"},
new SelectListItem() { Text = "apple", Value = "apple"},
new SelectListItem() { Text = "grapes", Value = "grapes"},
};
This will be used for binding with the asp.net mvc html helper. However I want to sort it before I bind it. How could i do this?
If you can use LINQ then:
list.OrderBy(x => x.Value)
or
list.OrderByDescending(x =>x.Value)
should do it.
edit
That should read;
list = list.OrderBy(x => x.Value);
Here you go:
List<SelectListItem> list = new List<SelectListItem>()
{
new SelectListItem() { Text = "apple", Value = "apple"},
new SelectListItem() { Text = "bob", Value = "bob"},
new SelectListItem() { Text = "grapes", Value = "grapes"},
};
Sorted:)
Sorry, couldn't stop myself:)
EDIT
It looks as if you needed:
var fruits = new List<string> {"apple", "bob", "grapes"};
fruits.Sort();
var fruitsSelectList = new SelectList(fruits);
and then in view
Html.DropDownList("Fruit",fruitsSelectList);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With