Sorting ASP.NET DropDownList Using LINQ

Posted by: Malcolm Sheridan , on 5/5/2009, in Category ASP.NET
Views: 69343
Abstract: The following article demonstrates how to use LINQ to sort data in an ASP.NET DropDownList control.
Sorting ASP.NET DropDownList Using LINQ
LINQ has been out since .Net 3.0 and it’s used to query in-memory data stores. I have been using LINQ for a while and I’m still amazed at how easy it is to perform tasks that otherwise would have required numerous lines of code to achieve the same result. Recently I was faced with a request on sorting items that were in an ASP.NET DropDownList control. It was not possible to order the data from the database, so I had to do this programmatically. My first thought was how can LINQ help me do this? In the following article I’ll show you how this was achieved with a few lines of code.
Open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application.
Open the Default.aspx page and add the following code:
<asp:DropDownList ID="cboNames" runat="server"></asp:DropDownList>
In the code above I have created an empty DropDownLst. Let’s add some data to the control. Open the code behind file for the page and add the following code to the page load event.
if (!IsPostBack)
      List<string> names = new List<string>() { "Malcolm", "Suprotim", "John", "Tony", "Alex", "Jason" };
      cboNames.DataSource = names;
If (Not IsPostBack) Then
      Dim names As New List(Of String) (New String() {"Malcolm", "Suprotim", "John", "Tony", "Alex", "Jason"})
       cboNames.DataSource = names
End If
I have created a generic List<string> to hold names of people. As you can see the data is not in any order. To order this data, the user would want to order in either an ascending and descending manner. To achieve this, we are going to use LINQ to make this a simple task. Go back to the aspx page and add the following buttons to the page:
<asp:Button ID="btnSortDescending" runat="server" Text="Sort Descending" OnClick="btnSortNames_Click" />
<asp:Button ID="btnSortAscending" runat="server" Text="Sort Ascending" OnClick="btnSortAscending_Click" />
The buttons above will handle the sort requests from the user. To achieve the sorting functionality, open the code behind file and add the following code:
protected void btnSortNames_Click(object sender, EventArgs e)
      cboNames.DataSource = cboNames.Items.Cast<ListItem>()
                            .OrderByDescending(o => o.Text)
protected void btnSortAscending_Click(object sender, EventArgs e)
      cboNames.DataSource = cboNames.Items.Cast<ListItem>()
                            .OrderBy(o => o.Text)
Protected Sub btnSortNames_Click(ByVal sender As Object, ByVal e As EventArgs)
      cboNames.DataSource = cboNames.Items.Cast(Of ListItem)().OrderByDescending(Function(o) o.Text).ToList()
End Sub
Protected Sub btnSortAscending_Click(ByVal sender As Object, ByVal e As EventArgs)
      cboNames.DataSource = cboNames.Items.Cast(Of ListItem)().OrderBy(Function(o) o.Text).ToList()
End Sub
Let’s run through the code and see where the magic happens. The Items property of the DropDownList control returns the collection of items in the control. To run a LINQ query against these items, we need to cast the items to the specified type because the items in the collection are non generic types:
cboNames.Items.Cast(Of ListItem)()
Once we have cast the items, we can use the standard query operators, OrderBy and OrderByDescending, to order the items in the collection. The query will not be executed until we call ToList(). ToList() executes the query and returns a generic List<ListItem> collection. That list is bound to the DropDownList by assigning it to the DataSource property. And finally DataBind is called to bind the data.
Hopefully this example shows you something you didn’t know about LINQ. Fingers crossed it gets you thinking on different ways you too can use LINQ to make your programming life easier.

The entire source code of this article can be downloaded from here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Kshitij on Wednesday, April 25, 2012 6:35 AM
Comment posted by Víctor Hernadez on Friday, June 1, 2012 3:48 PM
Great!!! thank you. This help me a lot.
Comment posted by Ludwig Van Fern on Tuesday, July 17, 2012 12:16 PM
Brilliant!! I ♥ LINQ XD
Comment posted by mskhan on Wednesday, October 10, 2012 10:16 AM
Great article!! Thanks so much!!
Comment posted by juan jimenez on Tuesday, February 18, 2014 1:11 PM
Thank you veryu much i served me well





C# Book for Building Concepts and Interviews



jQuery CookBook