Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
LeftbarAd
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » C# Lists: Add some elegance to your code

C# Lists: Add some elegance to your code

A short and to-the-point tutorial that demonstrates how to sort and search using C#'s List object.

Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads :
Total page views :  243302
Rating :
 5/5
This article has been rated :  7 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
ArticleAd
Become a Sponsor



It is a fairly common programming scenario to find ourselves with a list of identical objects. In the past, without adequate support from programming languages, we found ourselves writing a lot of searching and sorting code, and that may have put you off using lists in favour of arrays. All that has changed with C# (particularly 2.0) - its implementation of a list makes handling such lists remarkably easy.

For example, given the following class Person:

public class Person

{

          public int age;

          public string name;

          public Person(int age, string name)

          {

                   this.age = age;

                   this.name = name;

          }

}

We can create a list of Person objects and add six people like so:

List<person>people = new List<person>();

people.Add(new Person(50, "Fred"));
people.Add(
new Person(30, "John"));
people.Add(
new Person(26, "Andrew"));
people.Add(
new Person(24, "Xavier"));
people.Add(
new Person(5, "Mark"));
people.Add(
new Person(6, "Cameron"));

C#'s list mechanism provides us with a number of useful methods. Personally, I find ForEach, FindAll and Sort to be very useful. ForEach allows us access to each item in the list. FindAll allows us to search for objects in the list that match a specific condition. Sort allows us to sort the objects in the list. The following code demonstrates how we might use each of these methods:

Console.WriteLine("Unsorted list");

people.ForEach(delegate(Person p)
   { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

// Find the young
List<person> young = people.FindAll(delegate(Person p) { return p.age < 25; });
Console.WriteLine("Age
is less than 25");

young.ForEach(
delegate(Person p)
   { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

// Sort by name
Console.WriteLine("Sorted list, by name");
people.Sort(
delegate(Person p1, Person p2)
   {
return p1.name.CompareTo(p2.name); });

people.ForEach(delegate(Person p)
   { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

// Sort by age
Console.WriteLine("Sorted list, by age");

people.Sort(delegate(Person p1, Person p2)
   {
return p1.age.CompareTo(p2.age); });

people.ForEach(delegate(Person p)
   { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

And here is the output that we should expect:

Unsorted list
50 Fred
30 John
26 Andrew
24 Xavier
5 Mark
6 Cameron

Age is less than 25
24 Xavier
5 Mark
6 Cameron

Sorted list, by name
26 Andrew
6 Cameron
50 Fred
30 John
5 Mark
24 Xavier

Sorted list, by age
5 Mark
6 Cameron
24 Xavier
26 Andrew
30 John
50 Fred

Lists are powerful and result in fewer, and more elegant, lines of code. Hopefully this short example has demonstrated their ease and you will find yourself using them in your day-to-day development activities.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Craig Murphy
Craig Murphy is employed by a leading professional services consulting firm as a Systems Development Engineer. Craig is also an author, developer, speaker, Microsoft Most Valuable Professional and Certified ScrumMaster. He specialises in: XML, web services, XSLT, TDD, .net and XP. He has extensive experience with Borland Delphi spanning some 10 years. Apart from in-house software, Craig has written applications for major oil companies and local councils. He is currently using C# and Visual Studio 2005.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
ASC, DESC order?colin1/24/2007
How do we specifiy these for C# List Object? Thanks much!! -colin
Reply | Email | Delete | Modify | 
 
 
Re: ASC, DESC order?james2/8/2007
Look at how the sorting is done there, you have to manually specify how each term is compared. Otherwise the compiler wouldn't know which parts of a structure to sort by. So all you have to do is change that CompareTo to make it think 4 is more than 6 or 'A' is more than 'B'.
Reply | Email | Delete | Modify | 
 
Re: Re: ASC, DESC order?Einstein3/16/2007

Hi,
    Is it possible to sort by more than one column in a List.

Thanks.

Reply | Email | Delete | Modify | 
parametersAndre3/23/2007
i'd like to use a 'type' variable for the parameter of a list. How do i do that?
Reply | Email | Delete | Modify | 
point to Sessionwarren4/27/2009
Hi there, Is there possible to point this List to a specific session? like the Session["Username"]? i would like to use this method in a Cart System Email: warren@mieuxs.com
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved