Sort Items in an ASP.NET DropDownList using LINQ

Have you been looking out for a way to sort the items of an ASP.NET DropDownList using LINQ? Here’s a LINQ solution:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Sorting DropDownList Items</title>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:DropDownList ID="DropDownList1" runat="server">
<
asp:ListItem Text="Item3"></asp:ListItem>
<
asp:ListItem Text="Item1"></asp:ListItem>
<
asp:ListItem Text="Item4"></asp:ListItem>
<
asp:ListItem Text="Item5"></asp:ListItem>
<
asp:ListItem Text="Item2"></asp:ListItem>
</
asp:DropDownList>
<
br />
<
asp:Button ID="btnSort" runat="server" Text="Sort"
onclick="btnSort_Click"/>
</
div>
</
form>
</
body>
</
html>



C#

protected void btnSort_Click(object sender, EventArgs e)
{
List<string> listItems =
DropDownList1.Items.Cast<ListItem>().Select(item => item.Text).ToList();
listItems.Sort((a, b) => string.Compare(a, b));
DropDownList1.DataSource = listItems;
DropDownList1.DataBind();
}

VB.NET

Protected Sub btnSort_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim listItems As List(Of String) = _
DDL.Items.Cast(Of ListItem)().Select(Function(item) item.Text).ToList()
listItems.Sort(Function(a, b) String.Compare(a, b))
DDL.DataSource = listItems
DDL.DataBind()
End Sub

Before Sorting

image

After Sorting

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

4 comments:

Taphop said...

great stuff. Thanks for sharing.
http://taphop.net
http://tatca.vn

Raunak said...

Thank you very much

Anonymous said...

This idea works except that it destroys any value items that was part of the list.

Kevin Bailey said...

Does anyone have a solution for losing the values portion of the list items?