Creating and Using a C# SortedList

Part of the You Can Learn ASP.Net and C# series.
By Ken Brown
December 18, 2004

Download the Source Code

In this article we discuss the C# object known as a SortedList. The sortedList object is part of the System.Collections namespace and is inherited from IList.

When do you want to use a sorted list? Anytime you have an array of key value pairs that would be beneficial for you to have the keys sorted would be a good time to use the sorted list.

You need to be aware that you can have only one instance of each key. The sort is not on the combination of the key-value but of just the key.

The steps to be aware of include adding the System.Collections namespace to your using statements. Adding key value pairs to the sorted list. And accessing the SortedList object with a foreach loop or a specific key.

First step is to create a solution and then a new project within that solution. I named my project SortMyList.

On WebForm1.aspx add a ListBox object and name it lbKeyValue. We will display the key value pairs we create within this ListBox.

Drag two label controls and two TextBox controls onto the form. For Label1 change the Text Property to Key and for Label2 change the Text Property to Value.

For the TextBox objects give one an ID of txtKey and the other an ID of txtValue and place them under the label objects.

Drag and Drop one button control onto the form. The ID will be btnAdd with a Text property of Add.

The general idea is you will type in your key value pair and click on the add button to add them to our sorted list. You can just as easily type in a few key value pairs and then enter them all at one time within the code, but we are going to do it like this for now.

Go to the code for the form and place the following code within the class as we add an instance of a SortedList object. We only want one SortedList object. This is a good time to make sure you have a using statement for the System.Collections namespace. Placed in the using section of the code above the class declaration.

using System.Collections;

Double Click the ADD button so we can place some C# code behind for the form. Place the following code within the click event of the Add button.

string key = string.Empty; 
string values = string.Empty; 
//If key value is null then terminate the insertion 
//into the SortedList 
if (txtKey != null) 
	key = txtKey.Text.ToString(); 
	values = txtValue.Text.ToString(); 
First we are creating a string (key) and setting the string to an empty string or blank. We also do the same with the values string.

Next we will read the txtKey.Text field and check to see if it is a null value. If so we don't want to do anything. If it has a value then full steam ahead.

We read the txtKey.Text value and place it into our key string. It is okay if the txtValue field contains a null which we assign to the values string.

Then we add the values read from our text fields into our SortedList object. Following that step we need to display the SortedList in our ListBox, so we will create a method called ShowList that shows our sorted list.

private void ShowList() 
	//You need the IDictionaryEnumerator object to 
	//iterate thru the SortedList object 
	IDictionaryEnumerator ide = sortList.GetEnumerator(); 
	//Now you have a DictionaryEntry object that allows 
	//you to iterate and get all the key value pairs. 
	foreach (DictionaryEntry key in sortList) 
		lbKeyValue.Items.Add(key.Key.ToString() + " " + key.Value.ToString()); 
ShowList is fairly simple. We clear out any previous values in our ListBox object with lbKeyValue.ClearSelection().

Then we assign our SortedList object to an IDictionaryEnumerator object. This allows us to iterate through the SortedList object using GetEnumerator(). Now we have a collection and can use the foreach keyword to walk through the collection getting the key and value for each entry in our SortedList.

Now you are ready to run the program. Build and then run. Type in a value in the "key" text box. Type in another value in the "value" text box and click on the Add button. The information you entered in the text boxes should display in the ListBox.

Type in another key value combination and click on the Add button and another entry should show in the ListBox. Depending on the version of the .Net framework you are using the list you display should be sorted by key. I am running Windows XP with version 1.0 and my list is not sorting by key. But when I run the same program on a Windows 2000 box with .Net framework 1.1, then the list is sorted by key and does not allow me to add duplicate keys.

Another way to walk through the collection is by using a while statement shown in the following method.

private void ShowSortedList() 
	//You need the IDictionaryEnumerator object to 
	//iterate thru the SortedList object 
	IDictionaryEnumerator ide = sortList.GetEnumerator(); 
	while (ide.MoveNext()) 
		lbKeyValue.Items.Add(ide.Key.ToString() + " " + ide.Value.ToString()); 
This sample follows the same concept, still need to assign the sorted list to a DictionaryEntry object, but we use the while statement to iterate through the key value pairs.

Basically, as long there is another member of the SortedList then you can MoveNext and get to the next record. When there is no more records then you exit out of the while loop.

There is also the Current command to get the current record. The Reset command which resets the SortList to the first record.

The ContainsKey() command allows you to only go into the SortedList if it contains a certain Key. If there is no key with the specific word requested, then the method returns false.

if (sortList.ContainsKey("Bing")) 
	while (ide.MoveNext()) 
		lbKeyValue.Items.Add(ide.Key.ToString() + " " + ide.Value.ToString()); 
This was a little primer on the SortedList object. It can prove useful when you have Key value pairs and you want the keys sorted and then you want to get at specific members of the key value pairs. It is part of the System.Collections namespace and is inherited from IList.

Home| About Us | NewsLetters | Contact Us |

Copyright © 2004-2014 You Can Learn Series

You Can Learn Series Home Page You Can Learn Series
You Can Learn Series Home Page Home            About the creators of YouCanLearnSeriesAbout Us      Contact YouCanLearnSeriesContact Us      Site map of YouCanLearnSeriesSite Map      Privacy Policy of You Can Learn SeriesPrivacy Policy       Terms of Use of You Can Learn Series web siteTerms of Use       YouCanLearnSeries RSS feed for C# tips and tutorials     
C# and ASP.Net Programming TipsC# and ASP.Net      SQL Tutorial, tips and tricks for DBA'sSQL       Landscaping Tips for Home GardenersLandscaping       WeightLifting Tips for the Young and OldWeightLifting       Kennos BlogBlog       Good health TipsGoodHealth       Learn about Great Travel DestinationsTravel     Web Business TipsWeb Business            You Can Learn Series' Online StoreStore

You Can Learn C# and ASP.Net SeriesC# and ASP.Net
  Using Client Side Code with C# and ASP.NetClient Side Code
  Using Client Side State Management with C# and ASP.NetClient Side State Management
  Create a C# Class in Visual StudioCreate A Class
  Use A Class in C#Use A Class
  Create a Solution in Visual StudioCreate a Solution
  Create a Project in Visual StudioCreate a Project
  Create an RSS feed for your Web SiteCreate an RSS Feed
  Create an RSS feed for your Web SiteListItemCollection
  Set Events in ASP.NetSet Events ASP.Net
  Set Events in C#Set Events C#
  What is Session State and How to Use it.Session State
  Creating and Using the C# SortedList ObjectSortedList Object
  Stylesheet Tips for Visual Studio .Net and ASP.NetStyleSheet Tricks
  Using C# MethodsUsing Methods
  Pass Objects to MethodsPass Objects to Methods
  Pass Objects from MethodsPass Objects from Methods
  Using Client side State management like ViewState and Hidden fieldsView State
  LDAP, What is Lightweight Directory Access ProtocolWhat is LDAP
  Build an LDAP ReaderBuild an LDAP Reader
  Convert information from LDAP to a Web ServiceLDAP To Web Service
  Question of the dayQuestion of the Day

You Can Learn SQL SeriesSQL
You Can Learn Landscaping and Gardening SeriesLandscape Tips
You Can Learn WeightLifting SeriesWeightLift Tips
Kenno's BlogBlog
You Can Learn Good Health SeriesGood Health Tips
You Can Learn Good Series NewslettersNewsletters
Learn about Great Travel DestinationsTravel
You Can Learn Series Web Business TipsWeb Business Tips
Merchandise Available from You Can Learn SeriesMerchandise

Bill Welter - The Prepared Mind of a Leader

Americas Public Schools