tags:

views:

138

answers:

6

Hi

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?

+2  A: 

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);
griegs
You mean and be efficient and all... Pshhttt. :)
Josh
Yeah, my mistake. sorry
griegs
I tried this but it never sorts for me. I sorted by "text" though. I will try "value"
chobo2
Naw it does not seem to want to sort with orderby.
chobo2
Did you insert the code as i have it or did you do list = list.orderby...?
griegs
A: 
var sorted = (from li in list
             orderby li.Text
             select li).ToList();

Voila!!

Josh
A: 

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);
LukLed
Now that's funny!
griegs
And this is the fastest solution:)
LukLed
I figured someone would respond with this. I know I can do it by hand but I might be adding lots in the future and figured if there was an easy way to sort it will save me time.
chobo2
A: 

you can also sort it in the client side using javascript (jquery)

BTW if you know the elements of the list just sort them yourself :

List<SelectListItem> list = new List<SelectListItem> {
 new SelectListItem { Text = "apple", Value = "apple"},
 new SelectListItem { Text = "bob", Value = "bob"}, 
 new SelectListItem { Text = "grapes", Value = "grapes"}
 };
Yassir
A: 

list.Sort

List<SelectListItem> list = new List<SelectListItem>()

{ new SelectListItem() { Text = "bob", Value = "bob"},
new SelectListItem() { Text = "apple", Value = "apple"},
new SelectListItem() { Text = "grapes", Value = "grapes"}, };

list.sort;

Chuckie
List.sort() does not work. It comes with an error that it can't sort it.
chobo2
A: 

This is very good read on Sorting ASP.NET MVC using Linq

Rachel