Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an ASP.NET MVC dropdownlist?

Tags:

c#

asp.net-mvc

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?

like image 494
chobo2 Avatar asked Nov 08 '09 23:11

chobo2


2 Answers

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);
like image 73
griegs Avatar answered Oct 20 '22 02:10

griegs


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);
like image 36
LukLed Avatar answered Oct 20 '22 02:10

LukLed