7

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?

Red
  • 3,030
  • 3
  • 22
  • 39
chobo2
  • 83,322
  • 195
  • 530
  • 832
  • Would this be helpful to you, its from another similar question: http://stackoverflow.com/questions/188141/c-list-orderby-alphabetical-order – Anthony Forloney Nov 08 '09 at 23:20
  • No SelectListItem does not implement comparer the same way. It does not like this when I try to sort it like that. – chobo2 Nov 08 '09 at 23:55

9 Answers9

18

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);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
griegs
  • 22,624
  • 33
  • 128
  • 205
13

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
  • 31,452
  • 17
  • 82
  • 107
  • 2
    And this is the fastest solution:) – LukLed Nov 08 '09 at 23:31
  • 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 Nov 08 '09 at 23:54
2
var sorted = (from li in list
             orderby li.Text
             select li).ToList();

Voila!!

Josh
  • 44,706
  • 7
  • 102
  • 124
2

Isn't the idea of MVC to separate function and display? What if you want to reuse the same list with different orderings?

I'd have thought this would be best as it only sorts if for the specified control.

Add a property to the Model you are using for the view:

public SelectList Fruit { get; set; }

Populate that list in your constructor (I'm using Entity Framework):

model.Fruit= new SelectList(db.tblFruit.Select(f => new { Id = f.ID, Name = f.Name }), "ID", "Name", "[Select Fruit]");

Then add your select list:

@Html.DropDownListFor(x => x.ID, new SelectList(Model.Fruit.OrderBy(y => y.Text), "Value", "Text"), "-- Select One --", new { @class = "form-control" })
Red
  • 3,030
  • 3
  • 22
  • 39
  • @Html.DropDownListFor(x => x.ID, new SelectList(Model.Fruit.OrderBy(y => y.Text), "Value", "Text"), "-- Select One --", new { @class = "form-control" }) this was did the trick,thanks – Krish Jan 13 '16 at 07:29
0

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"}
 };
Hannoun Yassir
  • 20,583
  • 23
  • 77
  • 112
0

A very simple way to handle it in Controller:

ViewBag.change_week = new SelectList(db.weeks.OrderBy(x=> x.week_guid), "week_guid", "week_number");
0

To sort in place, use the sort function:

list.Sort((x, y) => x.Text.CompareTo(y.Text));
tdahman1325
  • 210
  • 3
  • 6
-1

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
  • 125
  • 2
-2

-------Store Procedure-----(SQL)

USE [Your Database]
GO

CRATE PROC [dbo].[GetAllDataByID]
@ID int


AS
BEGIN
        SELECT * FROM Your_Table
        WHERE ID=@ID
        ORDER BY Your_ColumnName 
END

----------Default.aspx---------

 <asp:DropDownList ID="ddlYourTable" runat="server"></asp:DropDownList>

---------Default.aspx.cs-------

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<YourTable> table= new List<YourTable>();
                YourtableRepository tableRepo = new YourtableRepository();



                int conuntryInfoID=1;
                table= tableRepo.GetAllDataByID(ID);

                ddlYourTable.DataSource = stateInfo;
                ddlYourTable.DataTextField = "Your_ColumnName";
                ddlYourTable.DataValueField = "ID";
                ddlYourTable.DataBind();



            }
        }

-------LINQ Helper Class----

public class TableRepository
    {
        string connstr;

        public TableRepository() 
        {
            connstr = Settings.Default.YourTableConnectionString.ToString();
        }

        public List<YourTable> GetAllDataByID(int ID)
        {
            List<YourTable> table= new List<YourTable>();
            using (YourTableDBDataContext dc = new YourTableDBDataContext ())
            {
                table= dc.GetAllDataByID(CID).ToList();
            }
            return table;
        }
    }
Sujith PS
  • 4,776
  • 3
  • 34
  • 61