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?

2
  • Would this be helpful to you, its from another similar question: stackoverflow.com/questions/188141/… Commented Nov 8, 2009 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. Commented Nov 8, 2009 at 23:55

9 Answers 9

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);
Sign up to request clarification or add additional context in comments.

5 Comments

You mean and be efficient and all... Pshhttt. :)
I tried this but it never sorts for me. I sorted by "text" though. I will try "value"
Naw it does not seem to want to sort with orderby.
Did you insert the code as i have it or did you do list = list.orderby...?
Worked for me sorting by text. Make sure to use list = list.OrderBy(...), though, because list.OrderBy(...) does nothing all by itself.
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);

2 Comments

And this is the fastest solution:)
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.
2
var sorted = (from li in list
             orderby li.Text
             select li).ToList();

Voila!!

Comments

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" })

1 Comment

@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
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"}
 };

Comments

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");

Comments

0

To sort in place, use the sort function:

list.Sort((x, y) => x.Text.CompareTo(y.Text));

Comments

-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;

1 Comment

List.sort() does not work. It comes with an error that it can't sort it.
-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;
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.