Covers topics on the Microsoft Certification Exam for the .NET Framework (Exam 70-536, Microsoft .NET Framework - Application Development Foundation)

Monday, April 14, 2008

How can you sort a list of strings in the .NET Framework?

The .NET Framework provides a simple efficient mechanism to sort a list of strings. The ArrayList class contains a Sort() method that allows the items in the ArrayList to be sorted in ascending order.

ArrayList Sort Example
using System;
using System.Collections;

// This is an example of using the .NET Framework and the
// Sort() method of the ArrayList class
namespace CollectionSortExample
{
class Program
{
static void Main(string[] args)
{
//Let's fill the ArrayList with some strings
ArrayList exampleList = new ArrayList();
exampleList.Add("C# Video Game Programming");
exampleList.Add("Really Thick Programming Book");
exampleList.Add("1984");
exampleList.Add("Alice in Wonderland");

//Print the list before it is sorted
Console.WriteLine("The unsorted list looks like:");
foreach (string item in exampleList)
{
Console.WriteLine("- {0}", item);
}

//Now we can do some "magic" and sort the
// ArrayList by caling the Sort() method.
exampleList.Sort();

//Print the list after it is sorted
Console.WriteLine("\n\nThe sorted list looks like:");
foreach (string item in exampleList)
{
Console.WriteLine("- {0}", item);
}
}
}
}

Output of ArrayList Sort Example

The unsorted list looks like:
- C# Video Game Programming
- Really Thick Programming Book
- 1984
- Alice in Wonderland

The sorted list looks like:
- 1984
- Alice in Wonderland
- C# Video Game Programming
- Really Thick Programming Book
Additional Resources
ArrayList Class (Microsoft)

1 comment:

Sarah Wilson said...

Thank you wizkid. I definately found this blog posting very helpful.

Support This Site

LinkShare  Referral  Prg