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

4 comments:

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

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

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

    ReplyDelete