|
|
|
|
C# Lists: Add some elegance to your code
By
Craig Murphy March 31, 2006
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 |
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
Related EbooksTop Videos
|
|
|
Description
|
|
LINQ for Visual C# 2005 is a short yet comprehensive guide to the major features of LINQ. It thoroughly covers LINQ to Objects, LINQ to SQL, LINQ to DataSet, and LINQ to XML.
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|