Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » C# Language » Add some elegance to your code using C# List

Add some elegance to your code using C# List

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

Page Views : 346290
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Mindcracker MVP Summit 2012
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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.


More related articles:

Merging two sorted linked lists in C#
FindAll(): Finding multiple items in C# List
Sorting a Generic List in C# 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
ASC, DESC order? by colin On January 24, 2007
How do we specifiy these for C# List Object? Thanks much!! -colin
Reply | Email | Modify 
Re: ASC, DESC order? by james On February 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 | Modify 
Re: Re: ASC, DESC order? by Einstein On March 16, 2007

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

Thanks.

Reply | Email | Modify 
parameters by Andre On March 23, 2007
i'd like to use a 'type' variable for the parameter of a list. How do i do that?
Reply | Email | Modify 
point to Session by warren On April 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 | Modify 
Re: point to Session by Bruno On November 13, 2010
Hello warrenphuang,

I suggest you to use a Dictionary for your sessions.

Look the following snippets I will write that may help you:


Declaring a new container. The string will be your key.

Dictionary<string,Session> objSessions = new Dictionary<string, Session>();

Then you will have a collection of session objects. Ready to be used.

Adding a new session to the collection:
           
string sessionID = System.Guid.NewGuid().ToString();
string username = "test user";


            // If does not exist. Add().
            if (objSessions.ContainsKey(sessionID) == false)
            {
                Session objTmp = new Session (userID, username);
                windows.Add(sessionID, objTmp);
                objTmp = null;
            }
            else
            {
                // Exactly how you wanna use it. Like Associative arrays that other languages implements.
                objSessions[sessionID].lastActivity = DateTime.Now;
            }


I just created the above example for a non-existing Session class.

Listing each object would be something like this:

                    foreach (Session tmp in objSessions.Values)
                    {
                                      System.Diagnostics.Debug.WriteLine("User:" + tmp.Username);
                   }



You should consider that Dictionaries and HashTables must have Unique keys.. and any valid type may be used as value.

The good thing about Dictionary type it to have lot's of built-in implementations for sorting, removing values.

Also you may use with LINQ if necessary.

Best wishes,
Bruno Ratnieks
Sniffer Networks do Brasil Ltda.
SNF
Reply | Email | Modify 
Thanks its working by David On June 9, 2010

Thanks for the helpfull article

Reply | Email | Modify 
Good work by Mahesh On January 28, 2011
Thanks for sharing Craig.
Reply | Email | Modify 
Binary Search On Sorted List by David On February 4, 2011
Hi Craig, nice article. This has really helped me out. How would I go about doing a binarysearch on your sortedlist. Say I was trying to find the index of "Fred" in your sorted list. Thanks.
Reply | Email | Modify 
Re: Binary Search On Sorted List by Mayur On November 29, 2011
Why comments posted on articles cant be copied
Reply | Email | Modify 
Nice explanation by Deepak On November 29, 2011
Good one Craig ! nice way to wrap up the concept of List in C#
Reply | Email | Modify 
welldone ! by Vikas On November 29, 2011
Thanks Craig for sharing this article ,it really help me to understand the use of c# list.
Reply | Email | Modify 
Amazing concept by Akash On November 29, 2011
Thanks Craig for such a useful article.
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.